从内容脚本访问窗口变量 [英] Access window variable from Content Script

查看:152
本文介绍了从内容脚本访问窗口变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果变量 window.my_variable_name 存在,我有一个Chrome扩展试图在每个浏览过的URL(以及每个浏览器URL的每个iframe)上查找。



因此,我编写了这段内容脚本:
$ b

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

尝试太久后,内容脚本似乎在某个沙箱中运行。 / p>

有没有方法可以从Chrome内容脚本访问窗口元素?


解决方案

内容脚本与当前页面共享相同的DOM,但它们不共享对变量的访问权限。处理这种情况的最好方法是从内容脚本向当前DOM中注入一个脚本标记,以读取页面中的变量。



在清单中.json:

 web_accessible_resources:[/js/my_file.js],

$ p $ <$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'函数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中:

  //从这里读取你的变量,并用它做一些事情
console.log(window.my_variable);


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 ?

解决方案

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);

这篇关于从内容脚本访问窗口变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆