How to tell when a page action is clicked when the page action has a popup

前端 未结 1 1572
时光说笑
时光说笑 2021-02-06 17:08

From https://developer.chrome.com/extensions/pageAction.html#event-onClicked:

chrome.pageAction.onClicked.addListener(function(tabs.Tab tab) {...});

相关标签:
1条回答
  • 2021-02-06 17:56

    When a popup is set, clicking on the button causes the popup page to be loaded and displayed. At the same time, the onClicked event will not be triggered. So, if you want to detect a click when a popup is set, put some code in popup.js.

    For instance: if your code without popup looks like:

    // background/event page
    chrome.pageAction.onClicked.addListener(function(tab) {
        // Do something
    });
    

    Then remove that piece of code from the background / event page, and put the code in popup.js:

    document.addEventListener('DOMContentLoaded', function() {
        // Do something, e.g. send a message to content or background script
    });
    

    If it's important to keep the logic in the background page, e.g. if you're initiating a http request, database access, etc., then use message passing to notify the background page that the button is being clicked:

    // popup.js
    chrome.runtime.sendMessage('pageActionClicked');
    
    // background.js
    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
        if (message === 'pageActionClicked') {
            // Do something
        }
    });
    

    If you have to know the current tab (like the tab argument in the pageAction.onClicked event), use chrome.tabs.query:

    // Inside the DOMContentLoaded or onMessage event listener:
    chrome.tabs.query({
        active: true,
        lastFocusedWindow: true
    }, function(tabs) {
        var tab = tabs[0];
        // Do something with tab
    });
    
    0 讨论(0)
提交回复
热议问题