0

Im sending a message from popup.js to background.js and am expecting the html body of the page, inside the message response. The problem is, that Im getting Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist. Below is my extension code:

manifest.json

{
  "manifest_version": 2,
  "name": "Chrome Extension",
  "version": "1.0",
  "description": "desc",
  "icons": {
    "16": "images/get_started16.png",
    "32": "images/get_started32.png",
    "48": "images/get_started48.png",
    "128": "images/get_started128.png"
  },
  "permissions": ["http://*/", "https://*/", "activeTab", "tabs", "storage"],
  "options_page": "options.html",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/get_started16.png",
      "32": "images/get_started32.png",
      "48": "images/get_started48.png",
      "128": "images/get_started128.png"
    }
  }
}

popup.js

'use strict';

let url;
let hostname;
let title;
let content;

// load data into the popup
function getData() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {}, function(response) {
            // get page url and title from tab and content from background script
            let urlObject = new URL(tabs[0].url);
            url = tabs[0].url;
            hostname = urlObject.hostname;
            title = tabs[0].title;
            content = response.content;
        });
    });
}

// on extension icon click
window.onload = function(){
    getData();
};

background.js

'use strict';

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log("ID: " + sender.id);
    sendResponse({content: body.innerHTML});
});
XuBo
  • 73
  • 1
  • 7
  • You might want to check https://stackoverflow.com/questions/13546778/how-to-communicate-between-popup-js-and-background-js-in-chrome-extension?rq=1 and https://developer.chrome.com/docs/extensions/reference/runtime/#method-sendMessage – Aziza Kasenova Jan 20 '21 at 17:02
  • 1
    Remove `background` section from manifest.json, rename `background.js` to `content.js` and [declare it properly](https://developer.chrome.com/extensions/content_scripts) in manifest.json. – wOxxOm Jan 20 '21 at 17:34
  • @wOxxOm Thank you. Looks like I didnt fully understand the uses of background and content scripts. It works now. – XuBo Jan 20 '21 at 17:50
  • @wOxxOm Would you like to post this as an answer, so I can mark it? – XuBo Jan 20 '21 at 17:59

0 Answers0