这似乎是最容易做的事情,但它就是行不通。在普通浏览器中,.html 和 .js 文件可以完美运行,但在 Chrome/Firefox 扩展中,onClick
函数没有执行它应该执行的操作。
.js文件:
function hellYeah(text) {
document.getElementById("text-holder").innerHTML = text;
}
.html 文件:
<!doctype html>
<html>
<head>
<title>
Getting Started Extension's Popup
</title>
<script src="popup.js"></script>
</head>
<body>
<div id="text-holder">
ha
</div>
<br />
<a onClick=hellYeah("xxx")>
hyhy
</a>
</body>
</html>
所以基本上一旦用户点击“hyhy”,“ha”应该变成“xxx”。再一次 - 它在浏览器中完美运行,但在扩展中不起作用。你知道为什么吗?以防万一,我还要在下面附加 manifest.json。
list .json:
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"http://api.flickr.com/"
]
}
最佳答案
Chrome 扩展不允许您使用内联 JavaScript ( documentation )。
Firefox WebExtensions ( documentation ) 也是如此。
你将不得不做类似的事情:
为链接分配一个 ID(<a onClick=hellYeah("xxx")>
变为 <a id="link">
),并使用 addEventListener
绑定(bind)事件。将以下内容放入您的 popup.js
文件:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
hellYeah('xxx');
});
});
popup.js
应作为单独的脚本文件加载:
<script src="popup.js"></script>
关于javascript - onclick 或内联脚本在扩展中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13591983/