Access window variable from Content Script [duplicate]

99封情书 提交于 2019-11-26 09:30:01

问题


I have a Chrome Extension that is trying to find on every browsed URL (and every iframe of every browser URL) if a variable window.my_variable_name exists.

So I wrote this little piece of content script :

function detectVariable(){
    if(window.my_variable_name || typeof my_variable_name !== \"undefined\") return true;
    return false;
}

After trying for too long, it seems Content Scripts runs in some sandbox.

Is there a way to access the window element from a Chrome Content Script ?


回答1:


One thing that is important to know is that Content Scripts share the same DOM as the current page, but they don't share access to variables. The best way of dealing with this case is, from the content script, to inject a script tag into the current DOM that will read the variables in the page.

in manifest.json:

"web_accessible_resources" : ["/js/my_file.js"],

in contentScript.js:

function injectScript(file, node) {
    var th = document.getElementsByTagName(node)[0];
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', file);
    th.appendChild(s);
}
injectScript( chrome.extension.getURL('/js/my_file.js'), 'body');

in my_file.js:

// Read your variable from here and do stuff with it
console.log(window.my_variable);


来源:https://stackoverflow.com/questions/20499994/access-window-variable-from-content-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!