JS - 将 SessionStorage 变量从父页面传递到 iFrame 弹出窗口? - 跨域

问题描述 投票:0回答:1

这是用 JavaScript 编写的。我希望将保存在父页面(域 https://parent.com/)上的 SessionStorage 中的变量传递到 10 秒后加载的 iframe 弹出窗口(域 https://iframe.com/) ).

我确信我必须使用 postMessage,但我似乎无法弄清楚。

任何帮助将不胜感激。谢谢!

javascript cross-domain postmessage
1个回答
0
投票

您需要在父窗口中使用 window.postMessage() 以及 iframe 中的 window.addEventListener() 来接收消息。确保在加载 iframe 时发送消息;否则,您的消息将会丢失。

此外,在监听消息时请注意消息的来源,忽略您不希望或不应该影响您的应用程序的消息。

您没有提到您是使用框架还是只是普通 JavaScript,因此实现可能会根据您的环境而有所不同。

如果它有用,我会在我的一个 React 项目中使用自定义挂钩来执行此操作。

function useMsgReceiver(options: MessageHandlerOptions) {
    const { origin, source, onMessage } = options;

    useEffect(() => {
        const handleMessage = async (event: MessageEvent) => {
            if (event.origin !== origin) return;
            try {
                const message = event.data;
                if (message.source !== source) {
                    console.error("Source not expected");
                    return;
                }
                await onMessage(message.type, message.payload);
            } catch (error) {
                console.error("Error while parsing the messagge: ", error);
            }
        };

        window.addEventListener('message', handleMessage);

        return () => {
            window.removeEventListener('message', handleMessage);
        };
    }, [onMessage, origin, source]);

这里我使用组件内部的钩子:

useMsgReceiver({
    origin: PARENT_ORIGIN,
    source: CUSTOM_SRC,
    onMessage: handleMessage
});

正如你所看到的,我对由源、有效负载和类型组成的交换消息使用类型定义来进行额外的检查,但如果你没有其他需求,你可以限制自己使用message.originmessage.data

© www.soinside.com 2019 - 2024. All rights reserved.