我正在使用此处描述的方法 1
Insert code into the page context using a content script
这是基于
Google Chrome "Application Shortcut": How to auto-load JavaScript?
这工作正常,但在我的浏览器 (Chrome) 更新到 v71 后,这不再工作,因为我的元素无法再在我注入(inject)的 JS 文件中找到函数。我准备了一个简单的例子:
list .json
{
"manifest_version": 2,
"name": "Test",
"version": "1.0.0",
"web_accessible_resources":
[
"Callbacks.js"
],
"content_scripts": [
{
"matches": ["https://stackoverflow.com/"],
"js": ["inject.js"],
"run_at": "document_idle"
}
],
"permissions": [
"activeTab"
]
}
注入(inject).js
function newButton(id, cb)
{
var b = document.createElement("div");
b.setAttribute("onclick",cb);
b.style.margin = "50px"
b.style.width = "100px";
b.style.height = "100px";
b.style.background = "gray";
b.style.zIndex = 10000000;
b.style.position = "absolute";
b.id = id;
return b;
}
var cc= document.createElement("script");
cc.src = chrome.runtime.getURL('Callbacks.js') ;
document.body.appendChild(cc);
document.body.appendChild(newButton("myId", "myfun();"));
Callbacks.js
function myfun(){
window.alert("hallo");
}
在访问 stackoverflow.com 并单击灰色 div 时,我在控制台中看到了这个
(index):1 Uncaught ReferenceError: myfun 未定义 在 HTMLDivElement.onclick ((index):1) onclick @(索引):1
但是,我仍然可以直接从控制台调用 myfun。
对此有什么想法吗?对于较旧的 Chrome 版本,这仍然有效。
最佳答案
如@wOxxOm 所述进行了重组,现在工作正常。
关于javascript - Chrome V71 打破了 Extension JS 注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53631642/