简体   繁体   中英

How can I get a localstorage of a webpage using a Firefox extension

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)

    });
});

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)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM