如何在Google Chrome扩展程序中检测到我登录到另一个网站?

Umb*_*bro 9 javascript google-chrome-extension reactjs

我有一个网络应用程序,并且为此做了一个附加的Google chrome扩展程序。如果我登录到网站,则如何在Google chrome扩展程序中检测到它,因此我不必再次登录扩展程序。当我登录到站点时,我希望扩展程序检测到我已登录到该站点并自动登录到该扩展程序。

我有以下错误:

无法加载内容脚本的JavaScript文件“ content.js”。

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'"
}
Run Code Online (Sandbox Code Playgroud)

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');
Run Code Online (Sandbox Code Playgroud)

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")
);
Run Code Online (Sandbox Code Playgroud)

popup.html

  <div id="app-container">
    <iframe width="500" height="500" src="https://app.com"></iframe>
  </div>
Run Code Online (Sandbox Code Playgroud)

更新资料

结构文件夹

//src
    //js
      //background.js
      //options.js
      //popup.js
//background.html
//manifest.json
//content.js
//options.html
//popup.html
Run Code Online (Sandbox Code Playgroud)

当我删除

"content_scripts": [{
    "matches": [ "*://*.app.com/*"  ],
    "js": [ "content.js" ],
    "all_frames": true
}]
Run Code Online (Sandbox Code Playgroud)

扩展正在加载

Ale*_*les 5

当用户已登录扩展程序正在使用的网站时,如何使用 chrome 扩展程序对用户进行身份验证。

这个答案有点宽泛,但最常见的身份验证方法通常是 2,要么通过 cookie,要么通过后端签名的令牌,然后告诉后端他正在与哪个用户交谈。

饼干:

如果身份验证是使用 cookie 完成的,那么您只需要在您的扩展程序中使用任一个,chrome.cookies这将允许您在后台脚本中使用 cookie。或者,如果 chrome 扩展程序正在使用内容脚本,那么您可以直接调用document.cookies以检索身份验证 cookie。

对于令牌认证:

如果你的应用程序碰巧使用的OAuth2例如,或者在向用户授予的访问令牌和存储在本地,使再认证agains的API有着相似的应用,那么你可以通过只调用其中的位置检索它token是保存。

如果令牌保存在localStorage您可以使用该get方法检索保存在那里的信息。在这里,您有更多关于它的文档 同样sessionStorage,如果令牌保留在那里,您可以访问此处还有更多文档