Установите localStorage для домена еще не загружен - PullRequest
0 голосов
/ 30 апреля 2020

Добрый день,

Я хочу установить localStorage в другой домен. Я использовал функцию postMessage. Вот родительская страница:

   <!DOCTYPE html>
<html>
<head>
    <title></title>
 <meta charset="utf-8" />
<script>
var childwin;
const childname = "popup";
function openChild() {
childwin = window.open('Page2.html', childname, 'height=300px, width=500px');

}
function sendMessage(){
    let msg={pName : "Bob", pAge: "35"};
    // In production, DO NOT use '*', use toe target domain
    childwin.postMessage(msg,'*')// childwin is the targetWindow
    childwin.focus();
}
</script>
</head>
<body>
    <form>
        <fieldset>
            <input type='button' id='btnopen' value='Open child' onclick='openChild();' />
            <input type='button' id='btnSendMsg' value='Send Message' onclick='sendMessage();' />
        </fieldset>
    </form>
</body>
</html>

Здесь дети:

<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script>
// Allow window to listen for a postMessage
    window.addEventListener("message", (event)=>{
// Normally you would check event.origin
        // To verify the targetOrigin matches
        // this window's domain
        let txt=document.querySelector('#txtMsg');
        localStorage.setItem("age", event.data.pAge);
        // event.data contains the message sent
        txt.value=`Name is ${event.data.pName} Age is  ${event.data.pAge}` ;

    });
    </script>
</head>
<body>
    <form>
        <h1>Recipient of postMessage</h1>
            <fieldset>
                <input type='text' id='txtMsg' />
            </fieldset>

    </form>
</body>
</html>

Это работает нормально, но нам нужно 2 кнопки. Один, чтобы открыть страницу, другой, чтобы опубликовать сообщение.

Если я хочу сделать два метода openChild (); postMessage () в одной кнопке, он не работает.

Я думаю, это потому, что страница 2. html загружается не полностью, когда мы вызываем postMessage ().

Как мы можем это сделать?

С уважением.

Кристоф.

1 Ответ

0 голосов
/ 30 апреля 2020

вы можете включить ваш скрипт при загрузке DOM

document.addEventListener('DOMContentLoaded', () => {

//do some functions

})
...