我正在构建一个Chrome扩展程序,并希望在用户单击Chrome中的浏览器操作图标时显示弹出窗口并运行脚本。

我可以通过在manifest.json中放置'“default_popup”:“popup.html”'来使弹出窗口发生。但是,当我这样做时,background.js似乎没有运行。当我删除'“default_popup”:“popup.html”'时,background.js似乎正在运行。

如何同时显示弹出窗口和脚本?

manifest.json

{
  "manifest_version": 2,

  "name": "Typo Blaster",
  "description": "Blast away typos and make the internet a safer place for the kids.",
  "version": "0.1",

  "browser_action": {
    "default_icon": "icon.png",
    "default_title": "Blast the typo!",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "icons": { "16": "icon16.png",
           "48": "icon48.png",
          "128": "icon128.png" }
}

popup.html
<!doctype html>
<html>
  <head>
    <title>Typo Blaster</title>
    <style>
      body {
        min-width: 357px;
        overflow-x: hidden;
      }

      img {
        margin: 5px;
        border: 2px solid black;
        vertical-align: middle;
        width: 75px;
        height: 75px;
      }
    </style>

    <script src="popup.js"></script>
  </head>
  <body>
    <h1>Got it!</h1>
  </body>
</html>

background.js
chrome.browserAction.onClicked.addListener(function(tab) {
  // No tabs or host permissions needed!
  console.log('Turning ' + tab.url + ' red!');
  chrome.tabs.executeScript({
    code: 'document.body.style.backgroundColor="red"'
  });
});

alert('hello ' + document.location.href);

最佳答案

弹出页面时,不能使用onClicked方法。 Google docs



如果您想同时保留两者,请考虑编写content script

10-05 20:36
查看更多