I have build a chrome extension and inside the chrome extension i created an iframe and in src field of iframe i pasted my application url. so whenever user open the extension it will open my application, But the issue is i want to store the user data(credentials, token) in such a way that if user open the extension in other pages/tabs the data(credentials, token) should be accessible, in my application im using localStorage to store the user credentials, but when user switches to other tabs, there is no information i localStorage
Example: User opened a coding platform leetcode and logged in my applition by opening extension, but when user switched to other tab, GFG then user is again asked to login
I want to store the user credentials such a way that it will only ask user once and the data should be accessible to different tabs
I tried by emitting an event through the extension background.js and i also added eventListner in my application but not able to receive the data which was sent through extension
content.js
window.addEventListener('message', function(event) {
const {href} = window.location
if(event.data.action === 'token-updated'){
console.log("token updated", event.data.token)
chrome.storage.local.set({ token: event.data.token }).then(() => {
console.log("Value is set", event.data.token);
});
chrome.storage.local.get(["token"]).then((result) => {
console.log("Value is " + result.token);
});
} else if (event.data.action === 'requestData') {
const key = event.data.key;
// Get the requested data from Chrome storage
chrome.storage.local.get([key], (result) => {
const data = result[key];
// Send the data back to the iframe
event.source.postMessage({ action: 'responseData', data: data }, event.origin);
});
}
});
manifest.json
{
"manifest_version": 3,
"name": "Api Analyzer",
"description": "Analyzes all ypu API's and give optimization of api tips",
"author": "Chary",
"version": "0.0.1",
"action": {
"default_icon": {
"16": "images/logo16.png",
"48": "images/logo48.png",
"128": "images/logo128.png"
}
},
"permissions": [
"storage",
"tabs",
"activeTab",
"declarativeContent"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"all_frames":true
}
],
"background": {
"service_worker": "background.js"
},
"icons": {
"16": "images/logo16.png",
"48": "images/logo48.png",
"128": "images/logo128.png"
},
"web_accessible_resources": [{
"resources": [
"images/*.png"
],
"matches": ["http://*/*", "https://*/*"],
"extension_ids": []
}]
}
background.js
chrome.action.onClicked.addListener(function (tab) {
console.log("ckicked")
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(request, sender, sendResponse)
if (request.action === 'requestData') {
sendResponse({data: { value: "my value"});
}
});