Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/content/messaging/0.installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,10 @@ websiteMessenger.onMessage('init', data => {
// initialize injected script

// eventually, send data back to the content script
websiteMessenger.sendMessage('somethingHappened', { ... });
// third and fourth parameter is optional
// third parameter is targetOrigin is additional optional value for postMessage which is default to '*'
// fourth parameter is reference of window object which is window on which message is passed passed in case of from iframe to Content Script(ie. parent window) it will be window.parent
websiteMessenger.sendMessage('somethingHappened', { ... }, '*', window.parent);
});
```

Expand Down
32 changes: 22 additions & 10 deletions docs/content/messaging/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ interface BaseMessagingConfig {

Shared configuration between all the different messengers.

### Properties
### Properties

- ***`logger?: Logger`*** (default: `console`)<br/>The logger to use when logging messages. Set to `null` to disable logging.

Expand All @@ -35,7 +35,7 @@ interface CustomEventMessage {

Additional fields available on the `Message` from a `CustomEventMessenger`.

### Properties
### Properties

- ***`event: CustomEvent`***<br/>The event that was fired, resulting in the message being passed.

Expand Down Expand Up @@ -153,7 +153,7 @@ interface ExtensionMessage {

Additional fields available on the `Message` from an `ExtensionMessenger`.

### Properties
### Properties

- ***`sender: Runtime.MessageSender`***<br/>Information about where the message came from. See
[`Runtime.MessageSender`](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/MessageSender).
Expand Down Expand Up @@ -196,6 +196,12 @@ interface GenericMessenger<
TMessageExtension,
TSendMessageArgs extends any[],
> {
sendMessage<TType extends keyof TProtocolMap>(
type: TType,
...args: GetDataType<TProtocolMap[TType]> extends undefined
? [data?: undefined, ...args: TSendMessageArgs]
: never
): Promise<GetReturnType<TProtocolMap[TType]>>;
sendMessage<TType extends keyof TProtocolMap>(
type: TType,
data: GetDataType<TProtocolMap[TType]>,
Expand Down Expand Up @@ -283,7 +289,7 @@ interface Message<

Contains information about the message received.

### Properties
### Properties

- ***`id: number`***<br/>A semi-unique, auto-incrementing number used to trace messages being sent.

Expand All @@ -306,7 +312,7 @@ interface MessageSender {

An object containing information about the script context that sent a message or request.

### Properties
### Properties

- ***`tab?: Tabs.Tab`***<br/>The $(ref:tabs.Tab) which opened the connection, if any. This property will <strong>only</strong>
be present when the connection was opened from a tab (including content scripts), and <strong>only</strong>
Expand All @@ -332,7 +338,7 @@ interface NamespaceMessagingConfig extends BaseMessagingConfig {
}
```

### Properties
### Properties

- ***`namespace: string`***<br/>A string used to ensure the messenger only sends messages to and listens for messages from
other messengers of the same type, with the same namespace.
Expand All @@ -354,7 +360,7 @@ Used to add a return type to a message in the protocol map.

> Internally, this is just an object with random keys for the data and return types.

### Properties
### Properties

- ***`BtVgCTPYZu: TData`***<br/>Stores the data type. Randomly named so that it isn't accidentally implemented.

Expand Down Expand Up @@ -392,7 +398,7 @@ interface SendMessageOptions {

Options for sending a message to a specific tab/frame

### Properties
### Properties

- ***`tabId: number`***<br/>The tab to send a message to

Expand All @@ -416,7 +422,7 @@ type WindowMessenger<TProtocolMap extends Record<string, any>> =
## `WindowSendMessageArgs`

```ts
type WindowSendMessageArgs = [targetOrigin?: string];
type WindowSendMessageArgs = [targetOrigin?: string, targetWindow?: Window];
```

For a `WindowMessenger`, `sendMessage` requires an additional argument, the `targetOrigin`. It
Expand All @@ -425,8 +431,14 @@ defines which frames inside the page should receive the message.
> See <https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#targetorigin> for more
details.

message is posted on window which can as per your need like
parent window in iframe -> window.parent
iframe content window -> iframe.contentWindow
opener original window -> window.opener
by default global window is used to send mesage

<br/><br/>

---

_API reference generated by [`docs/generate-api-references.ts`](https://github.com/aklinker1/webext-core/blob/main/docs/generate-api-references.ts)_
_API reference generated by [`docs/generate-api-references.ts`](https://github.com/aklinker1/webext-core/blob/main/docs/generate-api-references.ts)_
20 changes: 15 additions & 5 deletions packages/messaging/src/window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,14 @@ export interface WindowMessagingConfig extends NamespaceMessagingConfig {}
*
* > See <https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#targetorigin> for more
* details.
*
* message is posted on window which can as per your need like
* parent window in iframe -> window.parent
* iframe content window -> iframe.contentWindow
* opener original window -> window.opener
* by default global window is used to send mesage
*/
export type WindowSendMessageArgs = [targetOrigin?: string];
export type WindowSendMessageArgs = [targetOrigin?: string, targetWindow?: Window];
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can have kept targetWindow first and then targetOrigin but don't this to be released as major version


export type WindowMessenger<TProtocolMap extends Record<string, any>> = GenericMessenger<
TProtocolMap,
Expand Down Expand Up @@ -58,7 +64,11 @@ export function defineWindowMessaging<

let removeAdditionalListeners: Array<() => void> = [];

const sendWindowMessage = (message: Message<TProtocolMap, any>, targetOrigin?: string) =>
const sendWindowMessage = (
message: Message<TProtocolMap, any>,
targetOrigin?: string,
targetWindow?: Window,
) =>
new Promise(res => {
const responseListener = (event: MessageEvent) => {
if (
Expand All @@ -74,7 +84,7 @@ export function defineWindowMessaging<
const removeResponseListener = () => window.removeEventListener('message', responseListener);
removeAdditionalListeners.push(removeResponseListener);
window.addEventListener('message', responseListener);
window.postMessage(
(targetWindow ?? window).postMessage(
{ type: REQUEST_TYPE, message, senderOrigin: location.origin, namespace, instanceId },
targetOrigin ?? '*',
);
Expand All @@ -83,8 +93,8 @@ export function defineWindowMessaging<
const messenger = defineGenericMessanging<TProtocolMap, {}, WindowSendMessageArgs>({
...config,

sendMessage(message, targetOrigin) {
return sendWindowMessage(message, targetOrigin);
sendMessage(message, targetOrigin, targetWindow) {
return sendWindowMessage(message, targetOrigin, targetWindow);
},

addRootListener(processMessage) {
Expand Down