发送消息到offsreen
Some checks failed
test / Run tests (push) Failing after 13s
build / Build (push) Failing after 23s

This commit is contained in:
2025-02-12 18:07:34 +08:00
parent 36cf8ef5a7
commit 3c238bcdc8
5 changed files with 44 additions and 24 deletions

View File

@ -79,7 +79,7 @@ export default class GMApi {
console.log("xml request", request, con);
// 先处理unsafe hearder
// 再发送到offscreen, 处理请求
sendMessageToOffsreen("offscreen/gmApi/requestXhr", request.params);
sendMessageToOffscreen("offscreen/gmApi/requestXhr", request.params);
}
start() {
@ -87,29 +87,14 @@ export default class GMApi {
}
}
export async function sendMessageToOffsreen(action: string, data?: any) {
// service_worker通过chrome.scripting.executeScript调用window.postMessage主动发送消息
export async function sendMessageToOffscreen(action: string, data?: any) {
// service_worker和offscreen同时监听消息,会导致消息被两边同时接收,但是返回结果时会产生问题,导致报错
// 不进行监听的话又无法从service_worker主动发送消息
const ctx = await chrome.runtime.getContexts({
contextTypes: [chrome.runtime.ContextType.OFFSCREEN_DOCUMENT],
documentUrls: [chrome.runtime.getURL("src/offscreen.html")],
});
chrome.scripting.executeScript({
target: {
documentIds: [ctx[0]!.documentId!],
tabId: -1,
},
func: (message) => {
// 在页面上下文中执行的代码
window.postMessage(
{
type: "sendMessage",
daat: message,
},
"*"
);
},
args: [{ action, data }],
// 所以这里通过clients.matchAll()获取到所有的client,然后通过postMessage发送消息
const list = await clients.matchAll();
list[0].postMessage({
type: "sendMessage",
data: { action, data },
});
}

View File

@ -21,6 +21,30 @@ export default class ServiceWorkerManager {
group.on("preparationOffscreen", async () => {
// 准备好环境
this.mq.emit("preparationOffscreen", {});
const ctx = await chrome.runtime.getContexts({
contextTypes: [chrome.runtime.ContextType.OFFSCREEN_DOCUMENT],
documentUrls: [chrome.runtime.getURL("src/offscreen.html")],
});
console.log("ctx", ctx, chrome.runtime.getURL("src/offscreen.html"));
chrome.scripting.executeScript({
target: {
documentIds: [ctx[0]!.documentId!],
tabId: -1,
},
func: (message) => {
// 在页面上下文中执行的代码
console.log("tesss");
window.postMessage(
{
type: "sendMessage",
daat: message,
},
"*"
);
},
args: [{ action: "test", data: "test" }],
});
});
const resource = new ResourceService(group.group("resource"), this.mq);

4
src/types/main.d.ts vendored
View File

@ -3,7 +3,9 @@ declare module "*.tpl";
declare module "*.json";
declare module "*.yaml";
declare let sandbox: Window;
declare const sandbox: Window;
declare const clients: Clients;
declare namespace GMSend {
interface XHRDetails {