-
Hi, thanks for this great framework. I used Google to translate, hope you understand what I mean. I use createContentScriptIframe to create an iframe. I currently don't know how to send a message between the current tab and the iframe. This is what I'm doing right now: shared/messageing2.ts
currentTab - iframe.content.ts
on Iframe, /dialog.html (App.vue):
But when I click the button with the handleClick event, I don't see anything in the currentTab. I don't know where am I wrong? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Ahh, To get this working without a library: // inside the top frame
window.addEventListener("message", (event) => {
console.log("request:", event.data);
event.source.postMessage("response-data");
}); // inside your iframe
window.top.postMessage("request-data");
window.addEventListener("message", (event) => {
// Do something with the response
console.log("response:", event.data);
}, { once: true }); The reason the library doesn't work, is it sends messages to That said, you may run into CORS errors while sending these messages between frames... Instead, I recommend sending the message to the background, then sending the message back to the tab.
It seems complicated, but it's super easy: // messaging.ts
import { defineExtensionMessaging } from '@webext-core/messaging';
export interface ProtocolMap {
getDataFromTopFrame(data: YourRequestData): YourResponseData;
}
export const messaging = defineExtensionMessaging<MessagingProtocol>(); // inside the iframe
const response = await messaging.sendMessage("getDataFromTopFrame", { ... });
console.log({ response }); // inside the background
messaging.onMessage("getDataFromTopFrame", ({ sender, data }) => {
// Send the message back to the tab, and return the response
return await messaging.sendMessage("getDataFromTopFrame", data, sender.tab?.id);
}); // inside the top frame
messaging.onMessage("getDataFromTopFrame", ({ data }) => {
console.log("Getting data from top frame...", data);
// Do your top frame work and return a response
return { ... };
}); With this approach, you don't need to worry about CORS and it works on iframes at any depth (iframe in an iframe, in an iframe, etc). |
Beta Was this translation helpful? Give feedback.
-
Oh I understand. Thank you very much. |
Beta Was this translation helpful? Give feedback.
Ahh,
defineWindowMessaging
was more created for a website to send a message to a extension, rather than communicating with other frames on the same page... So that library will need some changes to get it working for your use-case.To get this working without a library:
The reason the library doesn't work, is it sends messages to
w…