Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: On browser action, create a pop up and execute a script

I'm building a Chrome extension and would like to show a pop up and run a script when the user clicks on a browser action icon in Chrome.

I can get the popup to occur by putting '"default_popup": "popup.html"' in manifest.json. However, when I do, background.js doesn't seem to run. When I remove '"default_popup": "popup.html"', background.js seems to run.

How can I get both the popup to appear and the script to run?

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);
like image 669
Corbin Page Avatar asked Sep 08 '14 21:09

Corbin Page


1 Answers

You can't use the onClicked method when you have a popup page. Google docs.

onClicked: Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.

If you want to keep both consider writing a content script.

like image 186
Daniel Avatar answered Sep 29 '22 16:09

Daniel