我是JavaScript和Google插件开发方面的新手。我正在尝试为它创建我的第一个扩展。我的目标是在维基百科页面上设置一个页面动作,在每次点击时显示简单的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!!!');
}问题是这个警报多次显示在屏幕上。在每一页重新加载后,它将显示两倍以上。例如:
等等..。
但我希望每次点击只显示一次提醒。我做错了什么?
发布于 2012-10-16 14:40:14
最初,您可以在加载文档时添加侦听器。在触发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!!!');
}https://stackoverflow.com/questions/12914779
复制相似问题