Accessing a pages object using a Chrome Extension

Viewed 1326

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 worlds in which the content scripts and injected scripts run and that it's possible to get some variables using the injected scripts and then send them back.

I have searched for other answers regarding this question and most work for other type of variables and are the basic way of doing it but none currently work for accessing objects.

Any current solutions or workarounds?

EDIT: The solution that I used:

Content script:

//Sends an object from the page to the background page as a string
window.addEventListener("message", function(message) {
    if (message.data.from == "myCS") {
        chrome.runtime.sendMessage({
            siteObject: message.data.prop
        });
    }
});
var myScript = document.createElement("script");
myScript.innerHTML = 'window.postMessage({from: "myCS", prop: JSON.stringify(OBJECT)},"*");';
document.body.appendChild(myScript);

Background.js:

//Info receiver
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {

    //When the content script sends the sites object to extract the needed data
    if (message.siteObject !== undefined) {
        console.log(message.siteObject);
        //Process the data
    }

});
2 Answers

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.

Related