google-chrome-extension - 从内容脚本访问窗口变量

标签 google-chrome-extension sandbox content-script

这个问题在这里已经有了答案:





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/

相关文章:

iframe - 带有 iframe "blocked a frame with origin from accessing a cross-origin frame"的 Chrome 扩展内容脚本

javascript - 使用扩展将按钮添加到文本字段 - 不可点击

google-chrome-extension - Popup.html 未在 Chrome 扩展中打开

ios - 将文件存储在 iPhone 中的沙箱外或通过其他应用程序访问文件系统

windows - 如何在 Windows 的沙箱中运行不受信任的代码?

javascript - 如何使用 "browser-action-jplib"监听 main.js 中的消息

Javascript、Chrome 扩展开发、关闭弹出窗口

javascript - 从 Chrome 扩展修改表的 insertRow

linux - Linux ptrace 怎么会不安全或包含竞争条件?

javascript - Chrome 将脚本注入(inject)上一个选项卡?