I want to add Listener to the event which fires, everytime the browser icon is clicked. I have also a popup which comes up on click on this icon.
I tried chrome.browserAction.onClicked.addListener()
but didnot get it fired, later i saw that the doc says:
Fired when a browser action icon is clicked.
This event will not fire if the browser action has a popup.
so, I have popup, so this Listener doesnot work. What workaround can I do to attach Listener to icon in my case?
There is no workaround to attach a listener to that event, but you can instead use messaging to let your background page know that the popup was opened.
In your popup, as soon as possible:
chrome.runtime.sendMessage({popupOpen: true});
In your background page:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
if(message.popupOpen) { /* do your stuff */ }
});
I needed something a bit more explicit for @Xan's answer, so here's what I did:
Here is my index.html
<!DOCTYPE html>
<html>
<head>
<title>Ahead of time compilation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="loader.js"></script>
<script src="popup.js"></script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
<script src="dist/build.js"></script>
</html>
Here is popup.js
chrome.runtime.sendMessage({popupOpen: true});
Here is manifest.json
{
"manifest_version": 2,
"name" : "Test ang 2",
"description" : "jons test",
"short_name" : "test",
"version" : "1.0",
"browser_action": {
"default_icon" : "app/assets/icon.png",
"default_title": "hi jon",
"default_popup": "index.html"
},
"permissions": [
"debugger",
"activeTab",
"tabs",
"alarms",
"clipboardWrite",
"notifications",
"background",
"storage",
"cookies",
"https://*/",
"http://*/"
],
"web_accessible_resources": [
"assets/*",
"bower_components/*",
"components/*",
"app.module.js",
"app.routes.js",
"index.html",
"app/*"
],
"externally_connectable": {
"matches": [
"*://*.capitalone.com/*"
]
},
"background": {
"scripts":["background.js"]
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content-scripts.js"]
}
],
"content_security_policy": "script-src 'self' ; object-src 'self'"
}
Here is background.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
console.log(message);
alert('hello world');
if(message.popupOpen) {
console.log('popup is open');
}
});
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