Umbro
Umbro

Reputation: 2204

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 alert. I don't have any errors or information in the console. Nothing displays in alerti console.log.

In localstorage I have key: auth,

{access_token:"1234567"
  expires_in: 86400
  refresh_token: "8906789"
  scope: null
  token_type: "Bearer"
}

manifest.json

{
  "manifest_version": 2,
  "name": "chrome extension",
  "description": "Chrome extension",
  "version": "0.0.1",
  "content_scripts": [
    {
      "matches": ["*://*.app.com/*"],
      "js": ["content.js"]
    }
  ],
  "browser_action": {
    "default_popup": "index.html",
    "default_title": "Open the popup"
  },
  "icons": {
    "16": "assets/icon-128.png",
    "48": "assets/icon-128.png",
    "128": "assets/icon-128.png"
  },
   "permissions": [
      "*://*.app.com/*",
      "storage"
  ],
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}

content.js

if (chrome && chrome.storage) {
  chrome.storage.sync.get('auth', function(result) {
    const item = result['access_token'];
    console.log(item);

    chrome.runtime.sendMessage(item, function(response) {
      console.log(response);
    });
  });
}

popup.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  alert('I am popup!');
  alert(message);
  console.log(message);
  console.log('I am popup!');
});

render(
  <App/>,
  window.document.getElementById("app-container")
);

UPDATED

manifest.json

{
  "name": "EXTENSION",
  "options_page": "options.html",
  "background": {
    "page": "background.html"
  },

  "content_scripts": [{
    "matches": [ "*://*.app.com/*"  ],
    "js": [ "content.js" ],
    "all_frames": true
}],
  "browser_action": {
    "default_popup": "popup.html",
    "default_icon": "icon-34.png"
  },
  "icons": {
    "128": "icon-128.png"
  },
  "permissions": [
   "https://*/",
   "http://*/",
   "*://*.app.com/*",
    "storage"
  ],
  "version": "1.0",
  "manifest_version": 2,
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}

content.js

if(chrome && chrome.storage){
  chrome.storage.sync.get('token', function(result){

    const item = result['access_token'];
    console.log(item);

    chrome.runtime.sendMessage(item, function(response) {
      console.log(response);
    });
  });
}


var port = chrome.runtime.connect({name: 'test'});
port.onMessage.addListener(function(msg, port) {
  console.log(msg);
});
port.postMessage('from-iframe');
popup.js

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
  console.log('popup got', msg, 'from', sender);
  sendResponse('response');
});

var iframePort; another function

chrome.runtime.onConnect.addListener(function(port) {
    iframePort = port;
    port.onMessage.addListener(function(msg, port) {
        console.log(msg);
    });
    port.postMessage('from-popup');
});

render(
  <App/>,
  window.document.getElementById("app-container")
);

popup.html

  <div id="app-container">
    <iframe width="500" height="500" src="https://app.com"></iframe>
  </div>

Upvotes: 0

Views: 517

Answers (1)

imlokesh
imlokesh

Reputation: 2729

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

Upvotes: 1

Related Questions