Chrome扩展程序:在浏览器操作中,创建弹出窗口并执行脚本

时间:2014-09-08 21:38:08

标签: javascript html json google-chrome-extension

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

我可以通过输入'' default_popup":" popup.html"'来获得弹出窗口。在manifest.json中。但是,当我这样做时,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);

2 个答案:

答案 0 :(得分:4)

当您有弹出页面时,无法使用onClicked方法。 Google docs

  

onClicked:单击浏览器操作图标时触发。这个事件不会发生   如果浏览器操作有弹出窗口。

如果你想两个人都考虑写一个content script

答案 1 :(得分:0)

尝试一下,

    chrome.browserAction.onClicked.addListener((tabs) => {
        chrome.tabs.executeScript(null,{file:"popup.js"})
    })

现在,当用户单击浏览器操作图标时,将执行文件popup.js