如何在谷歌浏览器扩展程序中检测到我已登录到另一个网站?



我有一个Web应用程序,我为它做了一个额外的谷歌浏览器扩展。如果我登录到该网站,如何在谷歌浏览器扩展程序中检测到它,这样我就不必再次登录扩展程序。当我登录到站点时,我希望扩展程序检测到我已登录到站点并自动登录到扩展程序。

我有以下错误:

无法为内容脚本加载 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'"
}

内容.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');

弹出窗口.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")
);

弹出窗口.html

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

更新

结构文件夹

//src
//js
//background.js
//options.js
//popup.js
//background.html
//manifest.json
//content.js
//options.html
//popup.html

当我删除时

"content_scripts": [{
"matches": [ "*://*.app.com/*"  ],
"js": [ "content.js" ],
"all_frames": true
}]

扩展正在加载

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

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

对于饼干:

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

对于令牌身份验证:

例如,如果你的应用碰巧使用 OAuth2,或者类似的实现,其中用户被授予访问令牌并存储在本地以进行身份验证,然后再次对 API 进行身份验证,那么你只需调用保存token的位置即可检索它。

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

确保content.jsmanifest.json位于同一文件夹中,或在manifest.json内更改其路径。

"content_scripts": [{
"matches": [ "*://*.app.com/*"  ],
"js": [ "PATH_TO_CONTENT/content.js" ], // Change this line
"all_frames": true
}],

为了检查您是否已登录,上面的答案是正确的,但听起来您真的在寻找为什么会发生Could not load JavaScript file的答案。

您应该将内容.js放入公用文件夹中,然后添加到 索引.html

<script src="%PUBLIC_URL%/content.js"></script>

最新更新