How to send page/tab information to the sidebar when developing a firefox extension?

I want to create a firefox extension where, amongst other things I need access to the URL I’m on.

Manifest.json

{....
"permissions": [
        "webNavigation",
        "storage",
        "<all_urls>",
        "tabs",
        "activeTab"
    ],
"background": {   "scripts": [  "background_script.js"  ]  },
    "sidebar_action": {
        "default_title": notes",
        "default_panel": "sidebar.html"
    },
}

As I understand it, in background_script.js I would have access to the dom and from there I would send information to the sidebar.

I should have more code for you but everything I tried was useless as if the sidebar and the current tab don’t want to share information with each other, but is there a way?

image

Hi,

No need for a background script. You can grab the current URL from the sidebar directly.

I took this demo extension and modified it to do what you want.

panel.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="panel.css"/>
  </head>

  <body>
    <p>Current URL is: <span></span></p>

    <script src="panel.js"></script>
  </body>
</html>

panel.js

const span = document.querySelector('span');
let myWindowId;

/*
Update the sidebar's content.

1) Get the active tab in this sidebar's window.
2) Update display in sidebar with active tab's URL
*/
function updateContent() {
  browser.tabs.query({windowId: myWindowId, active: true})
    .then((tabs) => {
      span.textContent = tabs[0].url;
    });
}

/*
Update content when a new tab becomes active.
*/
browser.tabs.onActivated.addListener(updateContent);

/*
Update content when a new page is loaded into a tab.
*/
browser.tabs.onUpdated.addListener(updateContent);

/*
When the sidebar loads, get the ID of its window,
and update its content.
*/
browser.windows.getCurrent({populate: true}).then((windowInfo) => {
  myWindowId = windowInfo.id;
  updateContent();
});

And that’s all there is to it. The actual code to grab the URL is in the updateContent function.

I’ve also stuck it up on GitHub if you want to try it out: https://github.com/jameshibbard/sidebar-url

Install via Addons manager > Cog Wheel > Debug Addons > Load Temporary Addon > select manifest.json.

HTH

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.