0

I'm trying to make a browser extension, when I click a button to get an API key stored in the local storage of a website. I have observed that I'm able to get the API key outside the event listener. However, when I do it inside of it always returns null. I was told that inside the event listener it is trying to get the local storage of the browser extension, so what can I do to overcome this issue? (I'm new to browser extensions)

Javascript:

let id = window.localStorage.getItem("session_id");
console.log(id)


document.addEventListener('DOMContentLoaded', function() {
    var api_button = document.getElementById('api_button');
    // onClick's logic below:
    api_button.addEventListener('click', function() {
        id = window.localStorage.getItem("session_id");
        alert(id)

    });
});
Giuca002
  • 3
  • 3
  • It probably means the site clears the id when that button is clicked. You can try running your code earlier by adding `,true` like this: api_button.addEventListener('click', function(){ ..... }, true) – wOxxOm Sep 05 '22 at 22:13
  • When I try that it still returns ``null``, I think what the issue is the id does the exist in the extension storage. However I'm not sure how to access the website local storage from inside of the EventListener. – Giuca002 Sep 05 '22 at 23:47
  • See [How to access the webpage DOM rather than the extension page DOM?](https://stackoverflow.com/q/4532236) – wOxxOm Sep 06 '22 at 05:47

1 Answers1

0

You want to use the storage API for this.

In your manifest.json, you need storage permission

"permissions": [
  "storage"
]

and then in your extension code, you can access the local storage with

browser.storage.local.set({ session_id: 'example' })

browser.storage.local.get('session_id').then((session_id) => {
    console.log(session_id)
})
Hamatti
  • 1,210
  • 10
  • 11