javascript - onclick 或内联脚本在扩展中不起作用

标签 javascript google-chrome-extension onclick firefox-addon-webextensions

这似乎是最容易做的事情,但它就是行不通。在普通浏览器中,.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/

相关文章:

javascript - 如何检测键盘事件已经绑定(bind)?

javascript - 内联 onclick 事件中的对象

java - 在java Activity 中循环遍历Android表格布局

安卓触摸监听器?

javascript - 在 three.js 中调整 dat.gui 的大小

javascript - 如何解决未捕获的类型错误: Illegal invocation jquery ajax

javascript - onclick 在表中添加新行

javascript - HTML CSS Make DIV 只要内容不是窗口

javascript - Chrome 扩展程序动态创建 HTML

javascript - 通过 Google API OAuth2 对用户进行身份验证以使用 Chrome 扩展程序