0

我有一个 google chrome 扩展程序,它在弹出窗口中显示 onclick。有一个上下文菜单,其中包含一些需要当前/活动选项卡 URL 的选项。该扩展程序存在如下所述的问题。

旧代码:

function menuCallback(info, tab) {

var currentUrl = tab.url;

使用旧代码:如果您在弹出窗口中右键单击,则返回的当前 url 是“chrome-extension ...”等等。

新代码:(我试图解决这个问题)

chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT},
    function(tabs){
        currentUrl = tabs[0].url;
    }
);

这有效,因为即使点击来自弹出窗口内部,它也会返回选项卡 url。但是,如果我有 10 个打开的标签并在两个之间切换,总是会返回旧的。例如我首先在 google.de,返回的 url 是 google.de。现在我切换到一个已经打开的标签,如“heise.de”并右键单击,它仍然是 google.de。下一次尝试/尝试 url 是否正确。

4

3 回答 3

1

You probably want to use the onUpdated listener.

chrome.tabs.onUpdated.addListener(doSomething);

Which gives you the tabId, changeInfo and tab metadata. You then can do as you please:

var doSomething = function (tabId, changeInfo, tab) {
  var match = /http:\/\/www.google.com/.exec(tab.url);
  if(match && changeInfo.status == 'complete') {
       ... do something ...
  } 
}

EDIT: After reading again your question, what you probably want is the onHighlighted event listener. It returns an object with an array of tabsIds and the window as soon as you select a tab.

chrome.tabs.onHighlighted.addListener(function(o) { tabId = o.tabIds[0]; })

You can then use get in order to obtain more information about that specific tab.

chrome.tabs.get(tabId, function(tab) { ... })

I'm leaving the onUpdated code in case anyone wants the tab information whenever a page changes.

于 2013-01-14T13:34:21.620 回答
0

使用查询参数在当前焦点窗口中查找活动选项卡的 URL 的最简单解决方案如下。

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
  currentUrl = tabs[0].url;
});
于 2014-07-10T13:26:51.617 回答
-1
chrome.tabs.getSelected(null, function(tab) {
    var currentURL= tab.url;
    alert(currentURL); // this should give you current url.
}
于 2013-01-15T05:44:48.310 回答