我非常喜欢JavaScript和谷歌浏览器的插件开发。我正在尝试为它创建我的第一个扩展。我的目标是在维基百科页面上有一个page action,它会在每次点击时显示简单的JS警报。我的代码如下:
// 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!!!');
}
问题是屏幕上多次显示警报。在每个页面重新加载后,它将显示两倍以上。例如:
依旧......
但我希望每次点击只显示一次警报。我做错了什么?
答案 0 :(得分:1)
您可以在文档加载时初始添加侦听器。在DOMContentLoaded事件被触发后,您需要添加侦听器:
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!!!');
}