PostMessage with multiple functions or custom callbacks

前端 未结 4 1044
刺人心
刺人心 2021-02-05 08:17

So far I\'ve only seen tutorials for postmessage where one window sends a single kind of message, and the other window interprets the message in only a single way.

What

4条回答
  •  长发绾君心
    2021-02-05 08:44

    One pretty easy way to trigger callbacks without passing any actual code would be:

    Target

    var callbacks = {
      myCallback: function() { doSomething(); }
    };
    window.addEventListener('message', function (ev) {
      // origin checking etc
      callbacks[ev.data]();
    }, false);
    

    Source

    target.postMessage('myCallback', 'http://www.example.com');
    

提交回复
热议问题