2

I'm developing an extension for Google Chrome and the problem I'm having is I need to be able to call a JavaScript function that belongs to the webpage that's opened in the tab.

For details, the website is my website, therefore I know that function does exist. That function does a lot of things based on a string value. I want the user to be able to highlight text on any webpage, click a button from the Chrome extension that automatically loads my webpage and calls that function with the highlighted text as it's value.

Here's what I got so far:

chrome.tabs.create({ url: "https://mywebsite.com" }, function (tab) {
    var c = "initPlayer('" + request.text + "');"; ////'request.text' is the highlighted text which works
    chrome.tabs.executeScript(tab.id, { code: c });
});

But Chrome console says: "Uncaught ReferenceError: initPlayer is not defined."

I know that function does exist as it is in my code on my own website.

Any help is highly appreciated. Thanks!

user2653364
  • 115
  • 2
  • 8
  • 1
    possible duplicate of [Building a Chrome Extension - Inject code in a page using a Content script](http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script) – Xan Dec 07 '14 at 17:54

1 Answers1

7

This happens because pages and content scripts run inside two separate javascript contexts. This means that content scripts cannot acces functions and variables inside a page directly: you'll need to inject a script into the page itself to make it work.

Here is a simple solution:

chrome.tabs.create({url: "https://mywebsite.com"}, function (tab) {
    var c = "var s = document.createElement('script');\
        s.textContent = \"initPlayer('" + request.text + "');\";\
        document.head.appendChild(s);"
    chrome.tabs.executeScript(tab.id, {code: c});
});

NOTE: since January 2021, use Manifest V3 with chrome.scripting.executeScript() instead of chrome.tabs.executeScript().

With the above code you will basically:

  1. Create the tab
  2. Inject the code (variable c) into it as a content script that will:
  3. Create a script with the code you want to execute on the page
  4. Inject the script in the page and, therefore, run its code in the page context
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128