2012-10-16 132 views
0

我是JavaScript中的新手,也是Google Chrome的插件开发人员。我正在尝试为它创建我的第一个扩展。我的目标是在维基百科页面上有一个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!!!'); 
} 

问题是,警报多次显示在屏幕上。每页重新加载后,它会显示两次以上。例如:

  • 打开网页
  • 点击我的插件图标
  • 警报显示2倍
  • 转到下一页
  • 点击图标
  • 警报显示4倍

等等...

但我想每次点击只显示一次警报。我究竟做错了什么?

+0

您反复添加监听...你只需要添加一次它时,插件首次加载 –

+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!!!'); 
} 
+0

感谢您的回答,它向我展示了寻找我需要的方向。在我的情况下页面内容不metter我只需要页面链接。因此,我需要另一个文件事件,如onPageLoadingStarted。 –