I have written a piece of code which alerts the tab URL after every 2 seconds. However, I am unable to do this for pop-ups. Whenever I open a pop-up; the tab url is of the background page and not the pop-up.
How can i get the url of the pop-up in crome?
<script>
var seconds = 2*1000;
setInterval(function(){
chrome.tabs.getSelected(null, function(tab) {
tabId = tab.id;
tabUrl = tab.url;
alert(tabUrl);
});
},secon开发者_如何学Cds);
</script>
</head>
When you pass null
instead of windowId
to chrome.tabs.getSelected()
, it defaults to "current" window, which is not necessary the selected one, as explained here:
The current window is the window that contains the code that is currently executing. It's important to realize that this can be different from the topmost or focused window.
So you need to find the focused window first, and then get its selected tab:
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);
In content_script.js or popup.html:
function get_urlInfo() {
var d = {
'action' : 'getUrl'
};
chrome.extension.sendRequest(d, function(response) {
alert(response.url);
});
};
In background.html:
function onRequest(request, sender, sendResponse) {
if (request.action == 'getUrl') {
sendResponse({'url' : sender.tab.url});
}
};
chrome.extension.onRequest.addListener(onRequest);
It should work!
精彩评论