Skip to content Skip to sidebar Skip to footer

Accessing A Pages Object Using A Chrome Extension

I simply have to access an object that is a variable on the page that I am running my content script on from my Chrome Extension. I know about the environments and their isolated w

Solution 1:

You can try to inject a script tag in the page to access the object. If needed, you could use messaging to communicate with your extension. For example, assuming the object you want to access in your page is called pageObject:

content1.js

//this code will add a new property to the page's object
var myOwnData = "createdFromContentScript";
var myScript = document.createElement("script");
myScript.innerHTML = "pageObject.myOwnData = " + myOwnData;
document.body.appendChild(myScript);

content2.js

//this code will read a property from the existing object and send it to background page

window.addEventListener("message", function(message) {
    if (message.data.from == "myCS") {
        chrome.runtime.sendMessage({theProperty: message.data.prop});
    }
});

var myScript = document.createElement("script");
myScript.innerHTML = 'window.postMessage({from: "myCS", prop: pageObject.existingProperty},"*");';
document.body.appendChild(myScript);

Solution 2:

No, there is no way. There is no point having the isolated worlds for security and then there being a workaround whereby an extension can hack the content script and variables if it really needs to.

Presumably the object on the page interacts with the page or has some effect on the page or something on the page affects the state of the variable. You can trigger actions on the page (via the DOM) that might change the state of that variable but you should stop looking for ways to access variables directly.

Of course if the page author is cooperative then it's a different ball game - a mechanism could be provided in the author's script, a getter and setter mechanism. But somehow I doubt that's what you're after.


Post a Comment for "Accessing A Pages Object Using A Chrome Extension"