Angular 5 访问由 window 打开的外部 window 对象 url 在 angular 5 中打开

Angular 5 to access an external window object url which is opened by window open in angular 5

您好,我已经使用 angular 5 使用以下方法

打开了一个 window
 var opened = window.open("localhost:4200/#/url");

以上代码将重定向到另一个外部 url。我想访问重定向 url.

我尝试了下面的代码

console.log(opened.location.href);

但是这样跟风

about:blank

同样的事情在javascript

中起作用
console.log(window.location.href);

我需要在 angular 5. 中做同样的事情。

请帮我解决问题。

提前致谢。

来自同一来源的两个 windows 之间的通信可以通过多种方式完成,其中一种方式是使用 localStorage 或 sessionStorage。 localStore 或 sessionStorage 变量值的变化可以在多个应用程序中监听 windows.

所以当你打开一个 child window 时,开始监听存储变量的变化,一旦 child window 加载,只需设置新加载的 URL 在本地存储中,以便 parent 可以捕获它。最后,只需删除事件侦听器即可。

希望对您有所帮助。

[更新的解决方案,在查看您的 stackblitz link] 后:

当我们以编程方式打开一个新的 window 时,我们知道它的初始 URL 状态将为空白,然后 javascript 开始运行并加载请求的 URL .但是,正如我们所知,Angular 在捕获原生 javascript 变量变化时总是有问题,同样的事情也发生在这里。 Angular 最近只知道初始状态 blank,但不知道加载的 URL。

要解决这个问题,也许你可以使用window.OnChildWindowLoaded

Parent:

export class AppComponent  {
  name = 'Angular';
  urlopened;
  opengoogle(){
    window.OnChildWindowLoaded = function (href) {
        console.log('Opened ' + href + ' successfully');
    };
    this.urlopened = window.open("https://stackblitz.com","");
  }
}

Child:

<script>
  window.onload = function () {
    window.opener.OnChildWindowLoaded(location.href);
  };
</script>

您可以通过 router Event 获得 Url :

像这样:

import { Component, NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Router, NavigationEnd,NavigationStart } from '@angular/router';

@Component({
  selector: 'my-app',
  template: 
    `<a routerLink='A'>A</a>
    <a routerLink='B'>B</a>
    <router-outlet></router-outlet>`,
})
export class AppComponent  {
  constructor(private router: Router) {}

   ngOnInit() {
    this.router.events.subscribe(event => {
          if(event instanceof NavigationStart) {
        console.log("NavigationStart",event.url)
        // alert('navigation succeeded');
      }
      if(event instanceof NavigationEnd) {
        console.log("NavigationEnd",event.url)
        // alert('navigation succeeded');
      }
    })
  }
}

@Component({
  selector: 'app-a',
  template: '<h1>A</h1>',
})
export class AComponent  {}

@Component({
  selector: 'app-b',
  template: '<h1>B</h1>',
})
export class BComponent  {}

const routes: Routes = [
  { path: 'A', component: AComponent },
  { path: 'B', component: BComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class RootRoutingModule { }

在这里您可以在 console.log.

中看到路由器 url