这个问题在这里已经有了答案:
Chrome extension - retrieving global variable from webpage
(5 个回答)
Hijacking a variable with a userscript for Chrome
(1 个回答)
8年前关闭。
我有一个 Chrome 扩展程序,它试图在每个浏览的 URL(以及每个浏览器 URL 的每个 iframe)上查找变量 window.my_variable_name
存在。
所以我写了一小段内容脚本:
function detectVariable(){
if(window.my_variable_name || typeof my_variable_name !== "undefined") return true;
return false;
}
在尝试了太久之后,似乎内容脚本在某些沙箱中运行。
有没有办法访问
window
Chrome 内容脚本中的元素?
最佳答案
重要的一件事是内容脚本与当前页面共享相同的 DOM,但它们不共享对变量的访问。处理这种情况的最佳方法是,从内容脚本中,将脚本标签注入(inject)当前 DOM 中,该标签将读取页面中的变量。
在 manifest.json 中:
"web_accessible_resources" : ["/js/my_file.js"],
在 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');
在 my_file.js 中:
// Read your variable from here and do stuff with it
console.log(window.my_variable);
关于google-chrome-extension - 从内容脚本访问窗口变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20499994/