【问题标题】:How can I get the current tab URL for chrome extension?如何获取 chrome 扩展的当前标签 URL?
【发布时间】:2011-05-25 23:13:13
【问题描述】:

我知道关于 SO 有很多类似的问题,但我似乎无法让它发挥作用。

我正在尝试从我的 Chrome 扩展程序中获取当前标签页的 URL。但是,警报(tab.url)返回“未定义”。我已在 manifest.json 中将“选项卡”添加到我的权限中。有什么想法吗?

<html>
<head>
<script>

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

        alert(tab.url);
    });

</script>
</head>

【问题讨论】:

  • 此方法已弃用。 take a look!
  • 有什么办法可以避免查询/投票,而是通过点击来确定活动标签?

标签: google-chrome google-chrome-extension


【解决方案1】:

仅供 Google 人员参考:

不推荐使用 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

  });

【讨论】:

  • 现在应该选择此方法,因为旧方法由于多种原因无法正常工作。
【解决方案2】:

问题出在这一行:

tab = tab.id;

应该是这样的:

var tabId = tab.id;

【讨论】:

  • 你错误地更改了变量选项卡...下次小心:)
  • getSelected 已弃用。请使用 tabs.query {active: true} tabs#method-getSelected
  • 您好,我需要聚焦标签信息..如果我在浏览器中有超过 5 个标签,如果点击(聚焦)标签 1,则点击“动作触发器”或标签 2/3 /4/5 .. 每次标签聚焦时它都应该触发。那么我该怎么办?
【解决方案3】:

这对我有用:

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

【讨论】:

    【解决方案4】:

    在 manifest.json 中:

    "permissions": [
        "tabs"
    ] 
    

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

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

        【解决方案6】:

        如果有人像我一样使用Web Extension Polyfill,以获得跨浏览器支持。

        // using async function
        const [currentTab] = await browser.tabs.query({
          active: true,
          currentWindow: true,
        });
        
        console.log({ id: currentTab.id, url: currentTab.url });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-21
          • 2011-07-08
          • 1970-01-01
          • 2015-12-27
          相关资源
          最近更新 更多