Chrome 拓展开发
网页呼出Popup
类似在网页中需要插件登录、授权等操作的时候呼出Popup 来做进一步的操作。
需要通过拓展中的Content Script
进行中转。
1.一个是网页(触发操作),通过window中的postMessage 发送一个操作如下。
document.getElementById('loginButton').addEventListener('click', () => {
// 向 Content Script 发送消息
window.postMessage({ type: 'EXTENSION_REQUEST', action: 'showAuthPopup' }, '*');
});
- 你需要创建一个 content-script 的插入脚本 在 manifest 文件中配置。
例如
"content_scripts": [
{
"matches": ["*://example.com/*"],
"js": ["content.js"],
"css": ["example.css"],
"run_at": "document_idle"
}
],
在文件中写入 以下内容,这里可以通过event.data
拿到网页发送的所有数据,这里根据业务需求可以做过滤,也可以只作为一个转发功能拿到data
后直接发送。
// content-script.js
window.addEventListener('message', (event) => {
if (event.data.type === 'EXTENSION_REQUEST') {
// 调用扩展的 API 向 Background Script 发送消息
chrome.runtime.sendMessage({ action: 'showAuthPopup' }, (response) => {
console.log('扩展响应:', response);
});
}
});
- 你需要创建一个 background-script 的worker脚本 在 manifest 文件中配置。
例如
"background": {
"service_worker": "/background.js"
},
在 Background Script
中接收 Content Script
发来的内容,这里使用 chrome.action.openPopup();
来呼出 Popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'showAuthPopup') {
// 尝试打开扩展的 popup
chrome.action.openPopup(); // 需要用户已配置图标或快捷键
// 如果失败,提示用户手动操作
if (!chrome.action.openPopup()) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon.png',
title: '授权请求',
message: '请单击插件图标进行授权登录'
});
}
sendResponse({ success: true });
}
});
评论 (0)