0

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>
Umbro
  • 1,984
  • 12
  • 40
  • 99
  • Possible duplicate of [Chrome extension: accessing localStorage in content script](https://stackoverflow.com/questions/3937000/chrome-extension-accessing-localstorage-in-content-script) – Salim Djerbouh Sep 22 '19 at 18:41
  • The popup is a separate page - with its own devtools and console - which runs only when shown (just like any other normal page) so it can't listen to messages when it's not shown. You'll need a background script - it'll always listen, but it's hidden so you'll want to change the way you're presenting the info, like maybe use a notification. Or you can insert the content script [programmatically](https://developer.chrome.com/extensions/content_scripts#functionality) from the popup script and use the result directly without messaging and without declaring it in manifest.json. – wOxxOm Sep 22 '19 at 18:44
  • @wOxxOm But when the popup appears, it should get the token. – Umbro Sep 22 '19 at 18:47
  • @wOxxOm If I use in 'background.js' --> `chrome.storage.sync.get('auth', function(result) { console.log(result); const item = result['access_token']; console.log(item); });` can I see console.log(result); ? – Umbro Sep 22 '19 at 19:22
  • "But when the popup appears" - it won't receive old messages which is why I suggested that the popup should use programmatic injection. As for the background script, [Where to read console messages from background.js in a Chrome extension?](//stackoverflow.com/q/10257301) – wOxxOm Sep 22 '19 at 19:55
  • @wOxxOm Inject Programmatically: So I have to go to the active tab example `www.app.com` then only read localstorage from this page? And if I was on a different tab and not on `www.app.com` then I would not read localstorage from this page` www.app.com`? – Umbro Sep 23 '19 at 08:07
  • Using the programmatic injection doesn't change the necessity to open the site first. It seems we don't yet understand each other. I'll venture a guess - if you want to read a site's localStorage without opening it in a tab then you'll have to open it in an iframe inside your popup or background script. And to run the content script there you'll have to declare it in manifest.json with "all_frames": true as shown in [content.js in iframe from chrome-extension popup](//stackoverflow.com/a/39901725) – wOxxOm Sep 23 '19 at 09:00
  • wOxxOm I updated the code. Could you look if I correctly configured `content.js`,` popup.js`, and `popup.html` with iframe? – Umbro Sep 27 '19 at 08:52
  • @Umbro can you explain what you need in the end? You click browser action and the local storage is loggged? Or you just open some site in a tab and the message is logged? – imlokesh Nov 18 '19 at 05:24
  • @imlokesh I made the extension to the main web application. When I am logged in to the main application and the tab is open. I click the extension icon (I want to fetch localstorage from an open tab -> main application). I don't wany to log in to the extension again, just fetch the token from the open application. Do you know what I mean now? – Umbro Nov 18 '19 at 09:45
  • @imlokesh can you help me? – Umbro Nov 18 '19 at 12:06

1 Answers1

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));
});
imlokesh
  • 2,506
  • 2
  • 22
  • 26
  • your browser-action it is my `popup.js`? In `manifest.json` I have to add ` "content_scripts": [{ "matches": [ "*://*.app.com/*" ], "js": [ "content.js" ], "all_frames": true }]` and `"permissions": [ "https://*/", "http://*/", "*://*.app.com/*", "storage" ],`? – Umbro Nov 18 '19 at 22:31
  • Yes browser action is popup js. You don't need permissions for all urls i think. – imlokesh Nov 19 '19 at 04:47
  • Do I have to set `
    ` in `popup.html` ?
    – Umbro Nov 19 '19 at 11:37
  • not required... but again i'm not sure what you're trying to do... if you try my code... and open a tab with app.com, then the content script sends data from storage to background script... then when you click popup, it gets that data from bg script... – imlokesh Nov 19 '19 at 11:47
  • In console.log I have errors: `Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.` `index.html:1 Error handling response: TypeError: Cannot read property 'error' of undefined`; ` Error handling response: TypeError: Cannot read property 'auth' of undefined`; ` – Umbro Nov 19 '19 at 11:55
  • sorry cannot help without seeing your full code... but in theory my solution should work... you can try searching for the errors you're getting – imlokesh Nov 19 '19 at 12:15
  • Is it possible to use console.log in `content-script` to read the result? It seems to me that localstorage content is not downloaded at all – Umbro Nov 19 '19 at 12:45