diff --git a/trame_iframe/widgets/iframe.py b/trame_iframe/widgets/iframe.py index ba660f7..e65e937 100644 --- a/trame_iframe/widgets/iframe.py +++ b/trame_iframe/widgets/iframe.py @@ -1,6 +1,7 @@ """IFrame Widgets support both vue2 and vue3 backend. """ +from typing import Optional from trame_client.widgets.core import AbstractElement from .. import module @@ -93,13 +94,14 @@ def post_message(self, msg): class Communicator(HtmlElement): _next_id = 0 - def __init__(self, event_names=[], **kwargs): + def __init__(self, event_names=[], parent_origin: Optional[str] = None, **kwargs): """ Create an invisible element that will allow a nested trame application to communicate with the iframe owner. Properties: :param event_names: List of string matching the expected emit topics from the child window. + :param parent_origin: Target origin we want to communicate to. If none, we assume same-origin. Events: @@ -117,12 +119,18 @@ def __init__(self, event_names=[], **kwargs): Communicator._next_id += 1 ref_name = f"trame_comm_{Communicator._next_id}" self.__ref = kwargs.get("ref", ref_name) + self._parent_origin = parent_origin super().__init__( "communicator", **kwargs, ) + self._attr_names += [ + ["parent_origin", "parentOrigin"], + ] self._attributes["ref"] = f'ref="{self.__ref}"' + self._attributes["parent_origin"] = f'parentOrigin="{self._parent_origin}"' + self._event_names += event_names def post_message(self, msg): diff --git a/vue-components/src/components/Communicator.js b/vue-components/src/components/Communicator.js index 71bf280..03f4349 100644 --- a/vue-components/src/components/Communicator.js +++ b/vue-components/src/components/Communicator.js @@ -1,11 +1,18 @@ import { inject, onMounted, onBeforeUnmount } from "vue"; export default { + props: ["parentOrigin"], setup(props, { emit }) { const trame = inject("trame"); + const parentOrigin = props.parentOrigin; + function postMessage(msg) { - window.postMessage(msg, "*"); + if (!parentOrigin) { + window.postMessage(msg, "*"); + } else { + window.parent.postMessage(msg, parentOrigin); + } } function triggerEmit(event) {