Communicate with iframe (same domain) using Angular 4/5

 ̄綄美尐妖づ 提交于 2019-12-24 07:28:14

问题


I am working on an application in which I need to display some components inside an <iframe>, so the <iframe> has the same origin.

I need to pass some values to this <iframe> (like logged in user information) from the parent component and the <iframe> can modify these values.

I know we can use window.postMessage to communicate with <iframe> that has a different origin and I can specify current origin to limit the exchange to only one origin. Is there a way apart from window.postMessage to communicate with an <iframe> that has the same origin?


回答1:


The Session Storage is a perfect way to communicate between iframes that belong to the same domain. Official docs

You can also bind to storage change events.

In pure JS you can just do this (JSFiddle here)

/* [Parent window] */
const writeToSessionEverySecond = function() {
    var value = 10;
    setInterval(function(){ 
      value++;
      sessionStorage.setItem('my_key', value);
    }, 1000);
}

writeToSessionEverySecond();


/* [Child window] Listen storage change events */
window.addEventListener('storage', function() {
    const valueFromSession = sessionStorage.getItem('my_key');
    console.log('VALUE ' + valueFromSession)
}, false);

NOTE: In order to really fire an event, the content of the session must change. If you set the same value the event wont fire.

If you are using RxJs you can use observables to build simple yet powerful logic on storage events streams, i.e,

Rx.Observable.fromEvent(window, 'storage').
              .<rx operators to do your magic>()
              .subscribe(..);

-Andrea



来源:https://stackoverflow.com/questions/50093664/communicate-with-iframe-same-domain-using-angular-4-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!