简体   繁体   中英

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: "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!

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});
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM