简体   繁体   English

通过 `chrome.storage.sync.get` 访问 'content.js' 中的 localstorage 并在 console.log 中显示令牌

[英]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.通过进入'matches' page: ["*: //*.app.com/*"]尝试在content.js中访问此页面的本地存储,并将令牌发送到popup.js并显示在 console.log 和作为警报。 I don't have any errors or information in the console.我在控制台中没有任何错误或信息。 Nothing displays in alerti console.log. alerti console.log 中没有显示任何内容。

In localstorage I have key: auth ,在本地存储中,我有密钥: auth

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

manifest.json 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内容.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 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 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内容.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 popup.html

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

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.这样,您只需打开一次应用程序即可将数据从本地存储保存到 bg 脚本,即使您在不同的选项卡上,浏览器操作仍将拥有您的身份验证令牌。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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