如何获取Chrome扩展程序的当前标签网址?

ryb*_*ybo 57 google-chrome google-chrome-extension

我知道在SO上有很多类似的问题,但我似乎无法让它发挥作用.

我正在尝试从Chrome扩展程序中获取当前标签的网址.Hoewever,警报(tab.url)返回"Undefined".我在manifest.json中添加了"tabs"到我的权限.有任何想法吗?

<html>
<head>
<script>

    chrome.tabs.getSelected(null, function(tab) {
        tab = tab.id;
        tabUrl = tab.url;

        alert(tab.url);
    });

</script>
</head>
Run Code Online (Sandbox Code Playgroud)

Jon*_*ine 113

只是来自谷歌的人的一个FYI:

不推荐使用OP使用的方法.要获取用户正在查看的选项卡,并且只在他们正在查看的窗口中使用此选项:

  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {

     // since only one tab should be active and in the current window at once
     // the return variable should only have one entry
     var activeTab = tabs[0];
     var activeTabId = activeTab.id; // or do whatever you need

  });
Run Code Online (Sandbox Code Playgroud)

  • 现在应选择此方法,因为由于多种原因,旧方法将不起作用。 (3认同)

ser*_*erg 29

问题出在这一行:

tab = tab.id;
Run Code Online (Sandbox Code Playgroud)

它应该是这样的:

var tabId = tab.id;
Run Code Online (Sandbox Code Playgroud)

  • 不推荐使用getSelected.请使用tabs.query {active:true} [tabs#method-getSelected](https://developer.chrome.com/extensions/tabs#method-getSelected) (4认同)

jay*_*ngh 8

这对我有用:

chrome.tabs.query({
    active: true,
    lastFocusedWindow: true
}, function(tabs) {
    // and use that tab to fill in out title and url
    var tab = tabs[0];
    console.log(tab.url);
    alert(tab.url);
});
Run Code Online (Sandbox Code Playgroud)


小智 7

在 manifest.json 中:

"permissions": [
    "tabs"
] 
Run Code Online (Sandbox Code Playgroud)

在 JavaScript 中:

chrome.tabs.query({
    active: true,
    lastFocusedWindow: true
}, function(tabs) {
    // and use that tab to fill in out title and url
    var tab = tabs[0];
    console.log(tab.url);
    alert(tab.url);
});
Run Code Online (Sandbox Code Playgroud)


小智 5

借助ES6的一点帮助,您可以轻松编写更好的代码:)

chrome.tabs.query({
  active: true,
  currentWindow: true
}, ([currentTab]) => {
  console.log(currentTab.id);
});
Run Code Online (Sandbox Code Playgroud)