在Firefox Addon中获取当前浏览器URL

Mar*_*ons 3 javascript firefox firefox-addon

我在一个面板中,我想获得当前的浏览器URL.到目前为止没有任何作品.这是我测试过的:

只有那些甚至可以返回任何内容的东西,我得到的东西resource://jid0-18z0ptaugyu0arjkaoywztggyzg-at-jetpack/,然后是我当前的面板资源 显然这是一个范围问题,但我不知道如何引用实际的浏览器.

window.location.href 
Run Code Online (Sandbox Code Playgroud)

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

如果有帮助,我使用的是Firefox Addon Builder.

小智 8

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

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

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

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

function getPage(){
  browser.tabs.query({currentWindow: true, active: true})
    .then((tabs) => {
      console.log(tabs[0].url);
  })
}
Run Code Online (Sandbox Code Playgroud)

从注入的 javascript 中获取 URL

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

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

"background": {
    "scripts": ["background.js"]
},

"content_scripts": [
    {
      "matches": ["https://www.*"],
      "js": ["modify-page/URL.js"]
    }
  ],
Run Code Online (Sandbox Code Playgroud)

这将通过 URL js 注入到网页中,并将向您的后台 js 发送消息以供使用。

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

service.postMessage({location: document.URL});
Run Code Online (Sandbox Code Playgroud)

此代码位于您的后台 js 中,并且会在每个新页面的 url 发生变化时收集它。

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);
Run Code Online (Sandbox Code Playgroud)


Fcz*_*bkk 7

// 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;
Run Code Online (Sandbox Code Playgroud)