【问题标题】:Google extensions: How to run a function in my javascript file when button is pressed in the popup?Google 扩展:当在弹出窗口中按下按钮时,如何在我的 javascript 文件中运行函数?
【发布时间】:2016-04-28 15:04:09
【问题描述】:

我正在开发一个谷歌扩展程序,我想通过按popup.html 中的按钮然后运行我的函数来更改 youtube.com 的背景颜色。

这是我的代码:

JavaScript 文件ms.js:

function color1(){
document.getElementById("body-container").style.backgroundColor="blue";}

HTML popup.html 文件:

<!DOCTYPE html>
<html>
<head>
<script src="ms.js">
</script>
</head>
<body>
<p> TEST </p>
<input type="button" value="blue" id="btn1" onclick="color1"/>
</body>
</html>

这是我的manifest.json 文件:

{

"name": "my extension test",

"version": "1.0",

"permissions": [
    "activeTab",
    "pageCapture"
],

"manifest_version": 2,

"description": "Test extension :D",

"browser_action": {
"default_icon": "ikon.png",
"default_popup": "popup.html"
},

"web_accessible_resources": [
"script/ms.js"
],

"content_scripts": [
    {
      "matches": ["https://www.youtube.com/*"],
      "js": ["ms.js"]
    }
  ]

}

【问题讨论】:

标签: javascript html google-chrome-extension


【解决方案1】:

更新

  1. 不需要内容脚本(通过manifest.json 注入),因此我们删除了content_scripts 部分
  2. 我们决定使用Programming injection,唯一需要的权限是activeTab,所以我们删除了activeTabpageCapture。如果您希望脚本在后台选项卡(非活动选项卡)中执行,则可以将activeTab 权限替换为主机权限。
  3. Web Accessible Resources 应该在我们期望在网页上下文中使用某些资源时使用,内容脚本本身不需要列入白名单,因此我们删除了 web_accessible_resources 部分
  4. 在文档中找到JavaScript就会执行,如果你把它包含在&lt;head&gt;标签中,&lt;body&gt;没有构造那么你可以找到元素,所以我们把它放在&lt;body&gt;的底部
  5. Inline Scripts 默认不会执行,所以我们把这个事件绑定逻辑移到外部脚本中。

看看chrome.tabs.executeScript,对于这样的小功能,你可以在页面中注入JavaScript代码。

manifest.json

{
    "name": "my extension test",
    "version": "1.0",
    "manifest_version": 2,
    "description": "Test extension :D",
    "browser_action": {
        "default_popup": "popup.html"
    },
    "permissions": [
        "activeTab"
    ]
}

popup.html

<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <p> TEST </p>
    <input type="button" value="blue" id="btn1" />
    <script src="ms.js">

    </script>
</body>

</html>

ms.js

document.getElementById("btn1").addEventListener("click", function() {
    chrome.tabs.executeScript({"code": 'document.getElementById("body-container").style.backgroundColor = "blue";'});
}, false);

【讨论】:

  • 代码转储纠正了多个错误/误解,但没有解释。
  • 我不同意将"activeTab" 替换为主机权限,但至少现在它是一个有价值的答案。
  • @Xan,提供了有关 activeTab 和主机权限的更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 2011-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
相关资源
最近更新 更多