问题
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