【问题标题】:Chrome extension can't inject code on button pressChrome 扩展程序无法在按下按钮时注入代码
【发布时间】:2017-07-08 20:00:14
【问题描述】:

我的简单 chrome 扩展程序不起作用。具体来说,当我单击弹出窗口中的按钮时,不会显示任何警报。 这是我的 manifest.json:

{"manifest_version": 2,
  "name": "Getting started example",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "<all_urls>"
  ],
"web_accessible_resources": ["page.js"]}

还有我的 popup.html:

<!DOCTYPE html>
<html>
  <head>
    <script src="popup.js"></script>
  </head>
  <body>
<button onclick = "a()">Alert!!</button>
</body>

</html>

还有我的 popup.js:

function a(){
    chrome.tabs.executeScript({code: "page.js"});
}

最后,我的 page.js:

alert("Hi from an extension!!");

但没有出现警报框。发生了什么?

【问题讨论】:

    标签: javascript html google-chrome-extension


    【解决方案1】:
    1. 嵌入的 js 代码在扩展页面中不起作用(您的 popup.html 中的 onclick 代码)。将其移动到单独的文件并使用例如addEventListener。弹出窗口的控制台中应该显示一个错误,不要忘记经常检查它:右键单击弹出窗口,然后Inspect
    2. 不需要"&lt;all_urls&gt;",因为您使用的是"activeTab"

      当用户调用扩展程序时,activeTab 权限使扩展程序可以临时访问当前活动的选项卡 - 例如通过单击其浏览器操作。对标签的访问将持续到标签被导航或关闭。

      这可作为 的许多用途的替代方案,但在安装过程中不显示警告消息。

    3. codechrome.tabs.executeScript 参数需要带有代码的文字字符串,而不是文件名。使用file参数。

    4. page.js 是一个内容脚本,它不是作为&lt;script&gt; 元素注入的,而是在"isolated world" 中运行, 所以不需要在“web_accessible_resources”中声明。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多