关于 javascript:在 Firefox Addon 中获取当前浏览器 url

Getting current browser url in Firefox Addon

我在面板中,我想获取当前的浏览器 URL。到目前为止没有任何效果。这是我测试过的:

唯一能返回任何东西的东西,我得到类似 resource://jid0-18z0ptaugyu0arjkaoywztggyzg-at-jetpack/ 的东西,然后是我当前的面板资源。显然这是一个范围问题,但我不知道如何引用实际的浏览器。

1
window.location.href

我已经尝试了最大的 Stack Overflow 线程中的所有内容:从 Firefox 侧边栏扩展中获取当前页面 URL。他们都没有返回任何东西。

如果有帮助,我正在使用 Firefox Addon Builder。


从侧边栏或弹出窗口获取 URL

要从侧边栏或弹出窗口检索 URL 需要选项卡权限

1
2
3
"permissions": [
   "tabs"
  ]

然后你需要找到你想要的标签。如果您只想要活动选项卡,这可以正常工作,对于更高级的任何内容,我会在这里查看。

1
2
3
4
5
6
function getPage(){
  browser.tabs.query({currentWindow: true, active: true})
    .then((tabs) => {
      console.log(tabs[0].url);
  })
}

从注入的 javascript 中获取 URL

如果您想要后台任务的 URL,我建议您使用此方法,因为您不需要权限。

这将为您提供一个后台脚本,然后将脚本注入到互联网上几乎所有网页上。

1
2
3
4
5
6
7
8
9
10
"background": {
   "scripts": ["background.js"]
},

"content_scripts": [
    {
     "matches": ["https://www.*"],
     "js": ["modify-page/URL.js"]
    }
  ],

这会通过URL js注入到网页中,并且会发送消息给你的后台js使用。

1
2
3
var service= browser.runtime.connect({name:"port-from-cs"});

service.postMessage({location: document.URL});

这段代码在你的后台js中,并且会随着它的变化收集每个新页面的url。

1
2
3
4
5
6
7
8
9
10
11
12
var portFromCS;

function connected(p) {
  portFromCS = p;
  portFromCS.onMessage.addListener(function(m) {
    if(m.location !== undefined){
      console.log(m.location);
    }
  });
}

browser.runtime.onConnect.addListener(connected);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// you need to use this service first
var windowsService = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator);

// window object representing the most recent (active) instance of Firefox
var currentWindow = windowsService.getMostRecentWindow('navigator:browser');

// most recent (active) browser object - that's the document frame inside the chrome
var browser = currentWindow.getBrowser();

// object containing all the data about an address displayed in the browser
var uri = browser.currentURI;

// textual representation of the actual full URL displayed in the browser
var url = uri.spec;


我相信使用 SDK 中的 API tabs 可以做到这一点:

1
2
3
// Get the active tab's title.
var tabs = require("tabs");
console.log("title of active tab is" + tabs.activeTab.title);

API 显示,为了检索当前标签 URL

1
2
3
4
5
   var URL = require('sdk/url').URL;
   var tabs = require('sdk/tabs');
   var url = URL(tabs.activeTab.url);

   console.log('active: ' + tabs.activeTab.url);

这将打印到控制台:" active: http://www.example.com"


对于插件,您可以使用以下代码从地址栏获取 URL

Javascript 代码:

1
2
3
4
function Doit(){
   var link = window.top.getBrowser().selectedBrowser.contentWindow.location.href;
   alert (link);
}

HTML 代码:

1
Generate URL

这将生成显示在浏览器当前选项卡上的 URL。


window 为您提供当前窗口。顶部为您提供最外框。