从Chrome扩展名中的popup.html文件在background.js文件中运行一个函数

Run a function in the background .js file from the popup .html file in a Chrome extension

本文关键字:文件 运行 函数 一个 js 扩展名 Chrome popup html background      更新时间:2023-09-26

我正在尝试编写一个Chrome扩展。您可以通过单击Chrome扩展图标在图标之间切换,popup.html会显示您将通过单击设置的图标的预览

<input type="image" src="icon.png" onclick="helloWorld()"></input>

函数helloWorld()在background.js文件中定义(同一目录:

chrome.browserAction.setIcon({
  path : "/iconcat.png"
});
function helloWorld() {
    chrome.browserAction.setIcon({
      path : "/icon.png"
    });
}

(首先要做的是将其设置为猫图标)

我将icon.pngiconcat.png以及.html和.js文件都放在同一目录中。

如何通过单击图像按钮来运行.js文件中的helloWorld()函数?

  1. 默认情况下,不会执行内联脚本。您应该提取onclick内联处理程序,并将其移动到像popup.js这样的外部脚本中。

  2. 要从弹出页面调用后台页面中的函数,您可以查看chrome.runtime.getBackgroundPage或chrome.extension.getBackgroundPage。

示例代码看起来像:

manifest.json

{
  "name": "Emoji",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Show an Emoji in Chrome!.",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "picker.html"
  },
  "background": {
    "scripts": ["background.js"]
  }
}

picker.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <input id="inputId" type="image" src="icon.png"></input>
    <script src="picker.js"></script>
</body>
</html>

picker.js

document.getElementById("inputId").addEventListener("click", function() {
    chrome.runtime.getBackgroundPage(function(backgroundPage) {
        backgroundPage.helloWorld();
    });
}, false);

background.js

chrome.browserAction.setIcon({
  path : "/iconcat.png"
});
function helloWorld() {
    chrome.browserAction.setIcon({
      path : "/icon.png"
    });
}