Get URL of selected tab from extension

I wrote a Firefox extension that requires the URL of the source document. Normally, JavaScript document.URLcould achieve this, but it is different.

See my example below:

shows the browser with several tabs opened and the extension panel displayed with a "fetch" button to alert the user to the current URL

As you can see, 4 tabs are open:

  • BBC Homepage
  • Add-in manager
  • Amazon.com
  • Stack overflow

And the StackOverflow.com page is currently being viewed (.. really).

My question is: how can I get the url of the active user window? (i.e. http://www.stackoverflow.com ).

Below is the code panel.html.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link href=panel.css rel="stylesheet" type="text/css">
    </head>
    <body>
        <header><h3>Where aM I</h3></header>          
        This Mozilla extension will display the current <i>background</i> URL
    <main>
        <fieldset>
            <legend>Click the Button</legend>
            <button onclick="PageViewing()">Fetch</button>
        </fieldset>
    </main>
    <script>
        function PageViewing() {
            alert(document.URL);
        }
    </script>
</body></html>

EDIT

If it is placed in a file main.js, this piece of code works:

    var tabs = require("sdk/tabs");
    console.log("URL of active tab is " + tabs.activeTab.url); //yields SO.com

, , P-Name/ lib, P-Name/ data​​strong > - ? Terminal output showing files and directory structure

+4
1

script. port.

main.js

panel.port.on('askactivetaburl', function(){
  panel.port.emit('sentactivetaburl', tabs.activeTab.url);
})

script

self.port.on('sentactivetaburl', function(activetaburl){
  // work with activetaburl
});

self.port.emit('askactivetaburl');
+2

Source: https://habr.com/ru/post/1539223/


All Articles