Access Localstorage In 'content.js' Via `chrome.storage.sync.get` And Display The Token In Console.log
By entering the 'matches' page: ['*: //*.app.com/*'] tries to access the localstorage of this page in content.js and send the token to popup.js and display in console.log and as an
Solution 1:
What you can do is have your content script save your auth data to a background script. You'll need a persistent background script for this. There's probably a better way to do what you're trying to do but i'm still not sure if i understand you correctly.
This way you only need to open your app once to save data from local storage to bg script and the browser action will still have your auth token even if you're on a different tab.
content-script
// Send auth token to background script
chrome.storage.local.get(['auth'], result => {
chrome.runtime.sendMessage({type: 'saveAuthToken', auth: result});
});
background-script
let authToken = null;
// Save auth token sent from content script
chrome.runtime.onMessage.addListener(msg => {
if(msg.type == 'saveAuthToken')
authToken = msg.auth;
});
// Handle auth token request from your browser action
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if(msg == 'getAuth')
{
if(!authToken){
sendResponse({error: 'Auth token not set. Please open app. '});
return;
}
sendResponse({auth: authToken});
}
});
browser-action
// Ask for auth token from background script
chrome.runtime.sendMessage("getAuth", response => {
if (response.error)
alert(response.error);
if (response.auth)
alert(JSON.stringify(response.auth));
});
Post a Comment for "Access Localstorage In 'content.js' Via `chrome.storage.sync.get` And Display The Token In Console.log"