【问题标题】:Run a function in the background .js file from the popup .html file in a Chrome extension从 Chrome 扩展中的弹出 .html 文件中运行后台 .js 文件中的函数
【发布时间】:2016-09-12 22:12:10
【问题描述】:

我正在尝试编写 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()函数?

【问题讨论】:

    标签: javascript html google-chrome-extension


    【解决方案1】:
    1. By default,内联脚本不会被执行。您应该提取您的 onclick 内联处理程序并将其移动到外部脚本,例如 popup.js

    2. 要从弹出页面调用后台页面中的函数,您可以查看chrome.runtime.getBackgroundPagechrome.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"
        });
    }
    

    【讨论】:

    • 所以基本上我应该把函数(helloWorld())放在popup.js而不是background.js中?
    • @Peanut,不完全是,helloWorld() 仍然可以放在background.js 中,因为你可以调用chrome.runtime.getBackgroundPage 来获取后台页面并调用其中的函数。
    • @Peanut,我的意思是你应该将你的内联处理程序提取到外部脚本,因为默认情况下不允许内联脚本。
    • 现在我对那个评论感到困惑。如果我让您查看包含所有内容的 GitHub 存储库怎么办?
    • @Peanut,这对调试您的问题很有帮助。
    猜你喜欢
    • 2021-10-20
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    相关资源
    最近更新 更多