Getting Current Browser Url In Firefox Addon
Solution 1:
getting the URL from a sidebar or popup
To retrieve the URL from a sidebar or popup requires tab permissions
"permissions":["tabs"]
then you need to find the tab you want. If you just want the active tab this would work fine, for anything more advanced I'd look here.
functiongetPage(){
browser.tabs.query({currentWindow: true, active: true})
.then((tabs) => {
console.log(tabs[0].url);
})
}
getting the URL from injected javascript
If you want the URL for a background task I suggest this method as you do not need permissions.
this will give you a background script and then inject a script onto almost any webpage on the internet.
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["https://www.*"],
"js": ["modify-page/URL.js"]
}
],
this will be injected into webpages through the URL js and will send a message to your background js to use.
var service= browser.runtime.connect({name:"port-from-cs"});
service.postMessage({location: document.URL});
This code is in your background js and will collect each new page's url as it changes.
var portFromCS;
functionconnected(p) {
portFromCS = p;
portFromCS.onMessage.addListener(function(m) {
if(m.location !== undefined){
console.log(m.location);
}
});
}
browser.runtime.onConnect.addListener(connected);
Solution 2:
// you need to use this service firstvar windowsService = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator);
// window object representing the most recent (active) instance of Firefoxvar currentWindow = windowsService.getMostRecentWindow('navigator:browser');
// most recent (active) browser object - that's the document frame inside the chromevar browser = currentWindow.getBrowser();
// object containing all the data about an address displayed in the browservar uri = browser.currentURI;
// textual representation of the actual full URL displayed in the browservar url = uri.spec;
Solution 3:
I believe using the API tabs
from SDK can do this:
// Get the active tab's title.var tabs = require("tabs");
console.log("title of active tab is " + tabs.activeTab.title);
Solution 4:
The API shows that in order to retrieve the current tabs URL
varURL = require('sdk/url').URL;
var tabs = require('sdk/tabs');
var url = URL(tabs.activeTab.url);
console.log('active: ' + tabs.activeTab.url);
This will print to the console: " active: http://www.example.com "
Solution 5:
window gives you the current window. top gives you the outermost frame.
Post a Comment for "Getting Current Browser Url In Firefox Addon"