【问题标题】:Display current URL in a chrome extension在 chrome 扩展中显示当前 URL
【发布时间】:2012-07-14 16:36:22
【问题描述】:

经过一番研究,我想出的代码是这样的:

var outUrl;
// first get the windowid
chrome.windows.getCurrent(function(window) {
    // then get the current active tab in that window
    chrome.tabs.query({
        active: true,
        windowId: window.id
    }, function (tabs) {
        var tab = tabs[0];
        document.write(tab.url)
    });
});

这是从我的弹出 html 文件调用的 javascript 文件中。但是,它不显示当前网站的 URL,而是什么都不显示。

我在这个网站和其他网站上找到了多篇关于此的帖子,但我无法实施任何假设的解决方案。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript google-chrome tabs google-chrome-extension


    【解决方案1】:

    也许这就是你要找的……

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

    并且需要在清单中设置tabs权限...

    manifest.json

    "permissions": [ 
      "tabs"
    ]
    

    【讨论】:

    • 我对此感到不确定。 :(
    • 知道了 - 必须添加这个:"permissions": [ "tabs" ] in manifest.json
    • ^ 然后在 chrome://extensions/ 页面重新加载扩展
    【解决方案2】:

    我有同样的问题。我编写了这个扩展来在弹出窗口中显示当前用户正在浏览的 URL。

    manifest.js

    "permissions": [ 
      "tabs"
    ]
    

    popup.js

    function getCurrentTabUrl(callback) {  
      var queryInfo = {
        active: true, 
        currentWindow: true
      };
    
      chrome.tabs.query(queryInfo, function(tabs) {
        var tab = tabs[0]; 
        var url = tab.url;
        callback(url);
      });
    }
    
    function renderURL(statusText) {
      document.getElementById('status').textContent = statusText;
    }
    
    document.addEventListener('DOMContentLoaded', function() {
      getCurrentTabUrl(function(url) {
        renderURL(url); 
      });
    });
    

    【讨论】:

      【解决方案3】:

      解决方案:

      获取当前选择的 Chrome 扩展标签的 URL 此代码用于获取部分 URL,因为在 tabs[0].url 中我们无法获取部分 URL,例如 host, hostname, origin, port, etc...

      chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
      let link = document.createElement('a');
      link.href = tabs[0].url;
      })
      

      进一步使用基本的 js 来获得它的部分: link.host = "密码记住.web.app" 您可以使用其他类似link.hostname, link.hash, link.host, link.href, link.origin, .link.pathname, link.protocol, link.search

      希望它能解决你的问题!

      【讨论】:

      • 别忘了在 Manifest.json 中设置 tabs 权限
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      相关资源
      最近更新 更多