我有一个 Chrome 扩展程序,它试图在每个浏览的 URL(以及每个浏览器 URL 的每个 iframe)上查找变量是否存在window.my_variable_name
exists.
所以我写了这个小内容脚本:
function detectVariable(){
if(window.my_variable_name || typeof my_variable_name !== "undefined") return true;
return false;
}
经过太长时间的尝试后,内容脚本似乎在某个沙箱中运行。
有没有办法访问window
Chrome 内容脚本中的元素?
需要了解的一件重要事情是,内容脚本与当前页面共享相同的 DOM,但它们不共享对变量的访问。处理这种情况的最佳方法是从内容脚本中将脚本标记注入到当前 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)