最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing object from injected page script to content script - Stack Overflow

programmeradmin4浏览0评论

I'm writing a chrome extension and I'm struggling to pass an object back from the main page to the content script. I can't seem to access the window's variables.

Content script

//STORE DATA TO CHROME STORAGE ON EVENT
//create hidden input
var hiddenInput = document.createElement("input");
hiddenInput.setAttribute("type", "text");
hiddenInput.setAttribute("id", "__HIDDEN__RESULT__");
//add input to page
var currentItem = document.body.appendChild(hiddenInput);
//event to be fired on click
currentItem.onclick = function() {
    //get the global variable window.listOfCourses and stick it in storage
    chrome.storage.local.set({'dataVault' : window.listOfCourses});
};

//inject script into page
var s = document.createElement("script");
s.src = chrome.extension.getURL("gradebook.js");
s.onload = function() {this.parentNode.removeChild(this);};
(document.head||document.documentElement).appendChild(s);

Injected page script

function processData()
{
    window.listOfCourses = [];

    for (i=0; i < windowpletedData.length; i++)
    {
        //get data and add to window.listOfCourses
    }
    var myElement = document.getElementById("__HIDDEN__RESULT__")
    myElement.click();
}

The injected script pulls information from a page, sticks it in an object set as global variable, then finally it fires the onclick event for the input.

All of this works. However, when the click event fires and runs currentItem.onclick() and tries to access window.listOfCourses, it doesn't see the variable. I'm confused why I'm not able to see my global variables anymore.

I'm writing a chrome extension and I'm struggling to pass an object back from the main page to the content script. I can't seem to access the window's variables.

Content script

//STORE DATA TO CHROME STORAGE ON EVENT
//create hidden input
var hiddenInput = document.createElement("input");
hiddenInput.setAttribute("type", "text");
hiddenInput.setAttribute("id", "__HIDDEN__RESULT__");
//add input to page
var currentItem = document.body.appendChild(hiddenInput);
//event to be fired on click
currentItem.onclick = function() {
    //get the global variable window.listOfCourses and stick it in storage
    chrome.storage.local.set({'dataVault' : window.listOfCourses});
};

//inject script into page
var s = document.createElement("script");
s.src = chrome.extension.getURL("gradebook.js");
s.onload = function() {this.parentNode.removeChild(this);};
(document.head||document.documentElement).appendChild(s);

Injected page script

function processData()
{
    window.listOfCourses = [];

    for (i=0; i < window.pletedData.length; i++)
    {
        //get data and add to window.listOfCourses
    }
    var myElement = document.getElementById("__HIDDEN__RESULT__")
    myElement.click();
}

The injected script pulls information from a page, sticks it in an object set as global variable, then finally it fires the onclick event for the input.

All of this works. However, when the click event fires and runs currentItem.onclick() and tries to access window.listOfCourses, it doesn't see the variable. I'm confused why I'm not able to see my global variables anymore.

Share Improve this question edited Mar 31, 2023 at 14:47 woxxom 73.7k14 gold badges156 silver badges160 bronze badges asked Nov 4, 2014 at 16:10 chris75898chris75898 951 silver badge8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 14

The global variables of a content script and a page-level injected script are isolated.

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.

Emphasis mine.

To pass the data to your content script, you don't have to employ extra DOM elements. You just need custom DOM events.

// Content script
// Listen for the event
window.addEventListener("FromPage", function(evt) {
  /* message is in evt.detail */
}, false);

// Page context
var message = {/* whatever */};
var event = new CustomEvent("FromPage", {detail: message});
window.dispatchEvent(event);

See this answer for far more details.

Above answer may work but I don't think it is the correct way ...

First:

If you already published your extension, get the application key and put it into your manifest "key" as described here:

  • install Chrome Extension Source Viewer
  • CRX -> view extension source -> enter published application URL -> enter
  • open developer tools (F12) -> go to console
  • copy the "key" atring from the console into your local manifest.json:

    "key": "MIIBIjANBgkqhkiG9w...RwIDAQAB",

This will ensure your local and published extension have the same extensionId

Second:

  • load your local extension
  • find out your extensionId by going to chrome://extensions and looking for ID under your extension title

Third:

in your background script (ie background.js) listen for msgs like this:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
   if (message.name === 'msg1') {
      alert(message.key1);
   }
});

in your content script (ie contentScript.js) send msgs like this:

chrome.runtime.sendMessage(extensionId, { name: 'msg1', key1: 'value1'}, undefined, (response) => {});

(replace extensionId with the one you got in the second step)

发布评论

评论列表(0)

  1. 暂无评论