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

I am trying to write a Chrome extension. You switch between icons by clicking the Chrome extension icon, and the popup.html comes up with a preview of the icon you will set it to by clicking:

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

And the function helloWorld() is defined in the background.js file (same directory:

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

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

(the first thing that is being done is setting it to a cat icon)

I have both icon.png and iconcat.png in the same directory as each other and the .html and .js files.

How can I get the image button to run the helloWorld() function in the .js file by clicking it?

Upvotes: 0

Views: 2188

Answers (1)

Haibara Ai
Haibara Ai

Reputation: 10897

  1. By default, inline script won't be executed. You should extract your onclick inline handler and move it to external script like popup.js.

  2. To call function in background page from popup page, you could take a look at chrome.runtime.getBackgroundPage or chrome.extension.getBackgroundPage.

Sample code looks like:

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"
    });
}

Upvotes: 2

Related Questions