user2653364 user2653364 - 2 years ago 205
Javascript Question

chrome.tabs.create/executeScript > call function that belongs to the page

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: "" }, function (tab) {
var c = "initPlayer('" + request.text + "');"; ////'request.text' is the highlighted text which works
chrome.tabs.executeScript(, { 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!

Answer Source

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: ""}, function (tab) {
    var c = "var s = document.createElement('script');\
        s.textContent = \"initPlayer('" + request.text + "');\";\
    chrome.tabs.executeScript(, {code: c});

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:
    1. Create a script with the code you want to execute on the page
    2. Inject the script in the page and, therefore, run its code in the page context
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download