Reputation: 1969
I'm totally newbie in JavaScript and in plugin development for Google Chrome. I'm trying to create my first extension for it. My aim is have a page action on wikipedia pages which show simple JS alert on each click. My code listed below:
// manifest.json
{
"name": "My Plugin",
"version": "0.0.1",
"manifest_version": 2,
"description": "My first expirience in plugin development for Google Chrome browser",
"page_action": {
"default_icon": "icon.png",
"default_title": "Action Title"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs"
]
}
// background.js
// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);
// Called when the url of a tab changes.
function checkForValidUrl(tabId, changeInfo, tab) {
// Show action only for wikipedia pages
var regex = /wikipedia.org/gi;
if (tab.url.match(regex)) {
chrome.pageAction.show(tabId);
chrome.pageAction.onClicked.addListener(onClickListener);
}
};
function onClickListener(tab) {
alert('Clicked!!!');
}
The problem is that alert showing on the screen multiple times. And after each page reload it will shows two times more. For example:
and so on...
But i want show alert only one time per click. What am I doing wrong?
Upvotes: 1
Views: 1926
Reputation: 5479
You can initially add your listeners when the document loads. You'll want to add your listeners after the DOMContentLoaded event has been fired:
document.addEventListener('DOMContentLoaded', function() {
chrome.tabs.onUpdated.addListener(checkForValidUrl);
//chrome.pageAction.onClicked.addListener(onClickListener); //might need to put this here, it's been a while since I've done a chrome extension, but if you do then just put your conditional for the regex in your onClickListener function
});
// Called when the url of a tab changes.
function checkForValidUrl(tabId, changeInfo, tab) {
// Show action only for wikipedia pages
var regex = /wikipedia.org/gi;
if (tab.url.match(regex)) {
chrome.pageAction.show(tabId);
chrome.pageAction.onClicked.addListener(onClickListener);
}
};
function onClickListener(tab) {
alert('Clicked!!!');
}
Upvotes: 1