2011-06-23 93 views
5

从我的知识来看,它不可能直接通过获取tab.url(只在popup.html中可能),并且做消息传递也需要popup.html打开。无论如何绕过这一点,并从background.html获取当前页面的网址?Chrome扩展程序:如何从background.html获取当前网页网址

我最好的拍摄是与消息传递,这是我在background.html

var bg = chrome.extension.getPopupPage(); 
var myURL = bg.myURL; 

然后在popup.html我用这个代码:

chrome.tabs.getSelected(null, function(tab) { 
    var myURL = tab.url; 
}) 

反正上面开不工作在所有。任何人都知道如何做到这一点,而不必实际打开弹出窗口?

回答

11

chrome.tabs.query支持从后台页面,当然只要你有tabs权限。这是支持的路线为Chrome浏览器19

chrome.tabs.query({ 
    active: true, 
    currentWindow: true 
}, function(tabs) { 
    var tab = tabs[0]; 
    var url = tab.url; 
}); 

注意,因为它会否则返回活动选项卡窗口currentWindow需要的。这应该保证只返回一个选项卡。

当然,请记住,这是一个异步API--除了在回调函数中,您不能访问它提供的任何数据。您可以将值(例如url)存储在更高的范围内,以便其他函数可以访问它,但在执行回调后仍然会提供正确的结果。


(下面是我原来的答复一直为后人 - 这个方法是不再需要,需要经常运行的后台页面,getSelected()已过时)

首先把这个背景.html和使myURL可变全球:

var myURL = "about:blank"; // A default url just in case below code doesn't work 
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { // onUpdated should fire when the selected tab is changed or a link is clicked 
    chrome.tabs.getSelected(null, function(tab) { 
     myURL = tab.url; 
    }); 
}); 

然后在popup.html运行时您希望得到的页面网址:

chrome.extension.getBackgroundPage().myURL; 

因此,如果我要让它出现在弹出窗口中,并且我去Google并点击了您的页面或浏览器操作,我会在弹出窗口中看到http://google.com/webhp

+0

谢谢!完美的作品。 – Calvin

1
chrome.tabs.getSelected(null, function(tab) { 
    var myURL = tab.url; 
}); 

我不明白,上面的代码可以在后台页面中使用,以获取当前选项卡的网址。

+1

从我的理解上面的代码将不会在后台页面工作,因为null值需要在后台windowid,但不弹出。 [来自评论的顶部回答](http://stackoverflow.com/questions/1979583/how-can-i-get-the-url-for-a-google-chrome-tab) – Calvin

+2

getSelected已被弃用。 – Soviut

2

看到这篇文章后,我觉得应该有一种方式来标记讨论为“过时”。

原因是...

这个问题需要迁移到体现v2和...
既没有工作的答案。我正在使用select onchange并发布当前选项卡的网址,该网址无效。

可能这些都在清单v1中工作。

我的回答是...

var myURL = "not set yet"; 
window.addEventListener('load', function() { 
    chrome.tabs.getSelected(null,function(tab){ 
     myURL=tab.url; 
    });  
+2

getSelected已弃用。 – Soviut

0

这是多一点的工作,但就像一个魅力...

我会用一个内容脚本;这是相对简单的&允许您从当前页面获取您可能需要的任何信息。让背景页面将脚本“注入”当前网页以收集您所需的信息。该脚本然后将其传回到背景。

background.js:

// Icon is clicked and triggers content script to be injected into current webpage 
chrome.browserAction.onClicked.addListener(function(tab) { 
    chrome.tabs.executeScript(null, { file: 'inject.js' }); 
}); 

// Listens for message back from content script and then runs 
chrome.runtime.onMessage.addListener(function (request) { 
    var URL = request.url; 
}); 

inject.js(内容脚本):

// Gathers up in the information that you need from webpage 
var pageInfo = { 
    "url": window.location.href 
}; 

// Sends the information back to background.js 
chrome.runtime.sendMessage(pageInfo); 

希望这可以帮助别人!

+1

不需要使用消息传递API,executeScript的回调包含内容脚本的最后一个表达式的值。哎呀,内容脚本根本不需要;在清单文件中声明'“标签”'权限后,您可以使用'tab.url'来获取标签的URL。 –

相关问题