0

I am developing an extension and want to make it interactive with my website. But when I try to call function that is located in the 'content_script.js' file it says that the functions is not defined!

Xan
  • 74,770
  • 16
  • 179
  • 206

1 Answers1

4

Step 1: Read about isolated context in which Content Scripts operate.

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

Step 2: Since you're interacting with your own website, the preferred method would be to employ messaging and externally_connectable property.

You need to declare in your manifest file that your extension is externally connectable from your site:

"externally_connectable": {
  "matches": ["*://*.example.com/*"]
}

In the webpage code, you need to message the extension by its ID:

// The ID of the extension we want to talk to.
var myExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";

// Make a simple request:
console.log("Sending ping from the page");
chrome.runtime.sendMessage(myExtensionId, {ping: true},
  function(response) {
    if(response.pong) console.log("Pong received from content script");
  }
);

Note: this function will only be exposed to the page if the extension is installed / externally connectable.

And finally, in your content script, react to that message:

chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    if (request.ping) {
      console.log("Ping received from the page");
      sendResponse({pong: true});
    }
  }
);

In general, read about Messaging to learn more.

Xan
  • 74,770
  • 16
  • 179
  • 206
  • How to send data from content script to webpage code? – Muhammad chhota Mar 11 '19 at 05:55
  • @Muhammadchhota Dispatch custom DOM events. As an example: https://stackoverflow.com/questions/25838804/gmail-extension-sendmessage-to-background-from-page-context/25847017#25847017 – Xan Mar 13 '19 at 12:39