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