Search code examples
javascriptsdkfirefox-addon-sdk

Get current URL


I'm looking to get the current url of the selected tab in firefox, I've got a Firefox SDK Panel directed at a contentURL and I've been using Javascript to try and fetch the current url;

window.content.location.href

But unfortunately it does not work unless im on my contentURL page any other pages and it displays nothing.

Thanks!


Solution

  • You can get the URL like this

    var url = require('sdk/tabs').activeTab.url;
    

    This works only inside your add-on code, not inside content scripts. For the difference see this guide.

    If you want to trigger the lookup from the content script and/or want to use the URL in the content script, you will have to communicate using "port".

    Here is an example in which the url of the current tab is displayed in the panel upon clicking a button.

    lib/main.js (add-on code):

    const data = require('sdk/self').data;
    
    var panel = require('sdk/panel').Panel({
        contentURL: data.url('panel.html'),
        contentScriptFile: data.url('panel.js')
    });
    
    panel.port.on('get url', function () {
        panel.port.emit('return url', require('sdk/tabs').activeTab.url);
    });
    
    panel.show();
    

    data/panel.js (content script):

    var button = document.getElementById('button');
    var urlspan = document.getElementById('url');
    
    button.addEventListener('click', function () {
        self.port.emit('get url');
    });
    
    self.port.on('return url', function (url) {
        urlspan.textContent = url;
    });
    

    data/panel.html:

    <!DOCTYPE html>
    <html>
      <head>
            <meta charset="utf-8" />
        <title>panel</title>
      </head>
      <body>
        <button id="button">
          Get Current URL
        </button>
        <br>
        Current URL: <span id="url"></span>
      </body>
    </html>