Chrome扩展程序:如何从background.html获取当前网页网址

时间:2011-06-23 09:07:01

标签: javascript url google-chrome-extension

据我所知,不可能通过获取tab.url(仅在popup.html中可能)直接进行消息传递也需要打开popup.html。反正有没有绕过这个并从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;
})

无论如何,上述情况根本不起作用。有人知道这样做的方法,而不必实际打开弹出窗口吗?

4 个答案:

答案 0 :(得分:17)

只要您拥有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()。)

首先将其放在background.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

答案 1 :(得分:2)

看到这篇文章后,我觉得应该有办法将讨论标记为“过时”。

原因是......

此问题需要迁移到清单v2和...
答案都不起作用。我正在使用select onchange并发布当前选项卡的url,这是无效的。

这些都可以在清单v1中使用。

我的回答是......

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

答案 2 :(得分:1)

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

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

答案 3 :(得分: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);

希望这有助于某人!