我正在编写一个非常简单的 chrome 扩展,它向当前页面添加一个按钮。
list .json
{
"manifest_version": 2,
"name": "chrome-extension-tabs-executescript-add-button-demo",
"description": "Chrome Extension Add Button Demo",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
popup.html
<!doctype html>
<html>
<head>
<title>Chrome Extension Add Button Demo</title>
<script src="popup.js"></script>
</head>
</html>
弹窗.js
chrome.tabs.executeScript({
file: "add-button.js"
}, function() {
console.log("add-button.js injected")
})
添加按钮.js
var button = document.createElement("button")
button.innerText = "This is the inserted button, click on me!"
button['id'] = 'inserted'
button['data-name'] = 'name1'
button.onclick = function() {
alert('clicked!')
}
button.fun = function() {
alert('fun!')
}
document.body.appendChild(button)
问题
如果我们单击当前页面的扩展程序图标,并在浏览器的控制台中键入以下代码,它几乎可以正常工作:
let button = document.getElementById('inserted');
button.click();
有警报表示它正在工作。
但是当调用 fun()
时:
button.fun();
它报告这样的错误:
Uncaught TypeError: button.fun is not a function
无法理解为什么缺少 fun
。
如果您需要,还提供一个简单但完整的演示:https://github.com/chrome-demos/chrome-extension-tabs-executescript-add-button-demo
我在其他答案中看到内容脚本 run in a "isolated world" ,页面和内容脚本只能看到相同的 DOM,但看不到彼此定义的变量。令我疑惑的是,onclick
和fun
都是定义在DOM 上的函数,为什么只有一个可以正常运行。
我猜,代码在内容脚本中运行
button.onclick = function() {
alert('clicked!')
}
button.fun = function() {
alert('fun!')
}
定义了两个函数,但它们不被认为是相同的。
onclick
是共享 DOM 的标准属性,因此它直接添加到 DOM 中,可以在页面上下文中看到。
但是 fun
方法不是,所以不会添加到共享 DOM,而是添加到其他地方(可能是共享 DOM 的子实例),只是留在Chrome 内容脚本的范围。
我的猜测是否正确?
最佳答案
你说得对。 网页和内容脚本共享相同的事件模型,但具有独立的变量和属性。
当您将函数分配给 button.onclick
时,您实际上为现有的事件模型设置了一个处理程序。 (顺便说一句,使用 onlick=
不是好的做法)。
但是通过将函数分配给 .fun
- 您正在创建一个新属性,它将与网页隔离。
关于javascript - 通过 chrome 扩展在当前页面插入一个按钮,但有些方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51398727/