首页 文章

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

提问于
浏览
49

我知道在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>

6 回答

  • 6

    这就是我获取tabID的方法:

    var queryStr = '?tabId=';
    var tabID = parseInt(location.search.substring(queryStr.length));
    
  • 28

    manifest.json =>

    “权限”:[“标签”]

    在js =>

    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);
            });
    
  • -3

    在ES6的帮助下,您可以轻松编写更好的代码:)

    chrome.tabs.query({
      active: true,
      currentWindow: true
    }, ([currentTab]) => {
      console.log(currentTab.id);
    });
    
  • 1

    问题出在这一行:

    tab = tab.id;
    

    它应该是这样的:

    var tabId = tab.id;
    
  • 92

    只是来自谷歌的人的一个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
    
      });
    
  • 1

    这对我有用:

    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);
    });
    

相关问题