2014-09-02 101 views
1

我试图获取当前域并在每个选项卡上使用扩展名更改时将其警告。例如,每当用户浏览另一个页面时,它将会为alert("your current path is: " + location.hostname);但它不起作用。我做错了什么?我想这样的代码:Chrome扩展程序获取每个选项卡上的当前域更改

chrome.tabs.onUpdated.addListener(
    alert(location.hostname); 
); 

回答

1

这不会工作,因为后台页面的location.hostname是铬://扩展URL。在ContentScript

// record active tab id when user switch tab every time 
// activeTabId is global variable 
var activeTabId = undefined; 
chrome.tabs.onActivated.addListener(
    function(activeInfo){ 
     activeTabId = activeInfo.tabId; 
    } 
); 

// send hostname request to content script when user update active tab 
chrome.tabs.onUpdated.addListener(
    function(changeInfo,tab){ 
     // check if the updating tab is active tab 
     if(tab.id === activeTabId){ 
      // send hostname request 
      chrome.tabs.sendMessage(activeTabId,{alertHostName:true}); 
     } 
    } 
); 

添加

"permissions": [ 
    "tabs" 
] 

然后更改您的代码:

chrome.tabs.onUpdated.addListener(function(){ 
    chrome.tabs.getSelected(null,function(tab) {//get current tab without any selectors 
     alert(tab.url); //get tab value 'url' 
    }); 
}); 
0

发送主机请求内容脚本

在background.js。 JS:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
     if (request.hasOwnProperty("alertHostName")){ 
      if(Boolean(request.alertHostName)){ 
       alert(location.hostname); 
      } 
     } 
    } 
); 
相关问题