简体   繁体   中英

onclicked event in popup.html from background.js

I would like to know simply if there's a way to set the background.js to do something if a specific element in popup.html is clicked, something like:

chrome.browserAction.getPopup(function(){
  document.getElementById('me').addEventListener('click', function(){
    /* do something ! */
  });
});

I am new to developing for Chrome extensions.

There are two ways to achieve what you're trying to do; both require a separate script in your popup.

  1. Call background page directly (simpler to implement). It's conceptually similar to what you were trying to do, but in the other direction.

    (this is covered by devnull69's answer )

  2. Message background page. It's cleaner in structure (you decouple how popup and background works) and will work if you move from popups to content scripts, as they cannot call the background directly.

background.js:

chrome.runtime.onMessage.addListener( function(message, sender, sendResponse) {
  if(message.from && message.from === "popup"){
    switch(message.action){
      case "doSomething":
        /* Do something */
        /* Maybe sendResponse(something) */
        break;
    }
  }
});

popup.js

function doSomethingAfterwards(response){
  /* Do something else */
}

document.getElementById('me').addEventListener('click', function(){
  chrome.runtime.sendMessage(
    {from: "popup", action: "doSomething"},
    doSomethingAfterwards
  );
});

Edit: for completion's sake only , I'm adding that there is a method chrome.extension.getViews that does what you initially wanted.

var popup = chrome.extension.getViews({type: "popup"})[0];
popup.document.getElementById('me').addEventListener('click', function(){
  /* do something ! */
});

But using it is not a very good idea: when do you invoke it? Your background page won't automatically receive a notification that your popup is opened (not even a chrome.browserAction.onClicked event if there is a popup), so it falls upon the first two methods to let the background know that the popup is open and ready.

I think you should "put the cart before the horse", ie think the other way round

Let's say, you want to execute the following method in your background script on click on an element of the popup:

function yourBackgroundMethod(parameter) {
   ...
}

If you click something in the popup, you can use Javascript from inside the popup to

  1. Add a click event listener to the element
  2. Inside the click handler you can get access to the background script (ie its window object) and execute code directly in the background script context

     chrome.runtime.getBackgroundPage(function(bgWindow) { bgWindow.yourBackgroundMethod(yourParameter); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM