2011-06-26 83 views
1

我寫了一段代碼,每隔2秒後提醒標籤URL。但是,我無法爲彈出窗口執行此操作。每當我打開一個彈出窗口;標籤網址是背景頁面,而不是彈出窗口。獲取Chrome彈出式窗口的URL

我怎樣才能得到在crome彈出的網址?

<script> 
var seconds = 2*1000; 
setInterval(function(){ 
    chrome.tabs.getSelected(null, function(tab) { 
     tabId = tab.id; 
     tabUrl = tab.url; 
     alert(tabUrl); 
}); 
},seconds); 
</script> 
</head> 
+1

你說的是哪彈出 - 擴展的彈出窗口或彈出窗口? – serg

+0

我的意思是彈出式窗口 – user782400

回答

0

在content_script.js或popup.html:

function get_urlInfo() { 
    var d = { 
     'action' : 'getUrl' 
    }; 

    chrome.extension.sendRequest(d, function(response) { 
     alert(response.url); 
    }); 
}; 

在background.html:

function onRequest(request, sender, sendResponse) { 
    if (request.action == 'getUrl') { 
     sendResponse({'url' : sender.tab.url});      
    } 
}; 

chrome.extension.onRequest.addListener(onRequest); 

它應該工作!

+0

不應該有一個點擊監聽器?因爲現在,當我點擊鏈接時,它顯示沒有提示 – user782400

+0

編號在你的setTimeout函數中調用get_urlInfo()。 – user278064

1

當通過null代替windowIdchrome.tabs.getSelected(),則默認爲「當前」的窗口,這是沒有必要的所選擇的一個,作爲解釋here

當前窗口是包含代碼的窗口目前正在執行。認識到這一點很重要,它可能與最頂層或關注的窗口不同。

所以,你需要先找到重點窗口,然後獲取其選中的標籤:

var seconds = 2*1000; 
setInterval(function(){ 
    chrome.windows.getLastFocused(function(window) { 
     chrome.tabs.getSelected(window.id, function(tab) { 
      tabId = tab.id; 
      tabUrl = tab.url; 
      alert(tabUrl); 
     }); 
    }); 
},seconds);