0

I want to open an external URL in a new tab from my Angular 8 SPA.

Answers to other questions suggest that you can use window.open(url, "_blank") to achieve this, and this works for me, but I am looking for something I can unit test.

Based on an answer to a different question, I have tried injecting the Document and calling document.open(url, "_blank") like so:

import { Component, OnInit, Input, Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";

@Component( ........ )
export class MyClass implements OnInit {

  private externalLink = "https://bbc.co.uk";

  constructor(@Inject(DOCUMENT) private readonly document: Document) { }

  ngOnInit() {
  }

  public navigate() {
    this.document.open(this.externalLink, "_blank");
  }
}

However, when this runs the screen goes immediately white and nothing else happens. No errors are logged to the console and placing a breakpoint in the method shows that the document is injected correctly as far as I can tell.

If this can't be resolved I am tempted to wrap a service around window.open() and inject that.

Toby Smith
  • 1,505
  • 2
  • 15
  • 24

2 Answers2

0

Use the this code

window.open(this.externalLink, "_blank");

instead of

this.document.open(this.externalLink, "_blank");

Hope this will help!!!

0

With no other answers being given, I did as I suggested I might in my question. I wrapped a small service around window.open like so:

import { Injectable } from "@angular/core";

@Injectable({
  providedIn: "root"
})
export class NewTabService {

  constructor() { }

  public open(url: string, newTab: boolean = false) {
    if (newTab) {
      window.open(url, "_blank");
      return;
    }

    window.location.href = url;
  }
}
Toby Smith
  • 1,505
  • 2
  • 15
  • 24