From https://developer.chrome.com/extensions/pageAction.html#event-onClicked:
chrome.pageAction.onClicked.addListener(function(tabs.Tab tab) {...});
Fired when a page action icon is clicked. This event will not fire if the page action has a popup.
So how do I tell when the page action is clicked if it DOES use a popup?
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With