Update Parent URL from Angular app inside Iframe

Viewed 168

I have an angular app inside an iframe. In the angular app I would like to update the Parent URL without reloading the page. I try to use 'window.parent.history.replaceState({},'',url);' but after some few seconds the page is being reloading.

any ideas?

1 Answers

use to:

<a href="#" onclick="top.window.location.href='yourURL';">

or===> I have completely copied the following answer from the enter link description here page.

  1. I am looking at doing something similar at the moment (a portal application with sub apps in an iFrame) You can communicate between your server and client (in either direction) by using window.postMessage to send data.

So for example on the server app:

var iframe = document.getElementById('useriframe');
    if (iframe == null) return;
    var iWindow = (<HTMLIFrameElement>iframe).contentWindow;

    iWindow.postMessage({"for":"user","data":"anything"}, 'http://localhost:4001');

  1. and on the client app (hosted within the iFrame)

export class AppComponent {

@HostListener('window:message',['$event'])
onMessage(e)
{
if (e.origin!="http://localhost:4200")
  {
  return false;
  }
if (e.data.for=="user")
  {
  alert('here i am');
  }
}

  1. Showing child frame routes in the parent So, in my implementation we pass tokens and user information from the shell application to the child iFrame, and we pass routing information from the child applications back to the shell so that the url reflects the route selected in the child application. In a child application you may have a route such as:

[userapp]/edituser/username

  1. and we wish to post it to the parent application and display the route like:

http://mywebsite/main/application/user#edituser/bob

  1. Note that we use hashtag to mark a child route, and in your child applications you intercept every navigation event and post the new route via

export class MyRoutingComponent implements OnInit {
constructor(private router: Router) { 
router.events.subscribe((event: Event)=>{
  if (event instanceof NavigationEnd){
        let url=(<NavigationEnd>event).url;
        if (url.length>1)//don't post message about base route '/'
          window.parent.postMessage({"for":"dashboard", "operation":"changeroute","route":url},'*')
  }

})
}

  1. and then in the parent application parse the message and use it to update the location path displayed.

  url = url +'#' + route;            
    this.location.go(url);

Related