2

How do you implement window.open() kind of functionality in Angular 4?

function open(){
    var URL = "file:///C:\data2.pdf";

    window.open(URL, null);
}

I am getting the below error message:

Cannot open local file - Chrome: Not allowed to load local resource.

Let me know if there is any alternative of window.open() in Angular 4.

Daniel W Strimpel
  • 8,190
  • 2
  • 28
  • 38
david d
  • 43
  • 1
  • 2
  • 4
  • The issue isn't with `window.open(...)` it is with the URL you are trying to open. It is a security issue to open local files using `file://` in Chrome. – Daniel W Strimpel May 11 '18 at 03:48
  • [angular-2-redirect-to-an-external-url-and-open-in-a-new-tab](https://stackoverflow.com/questions/42775017/angular-2-redirect-to-an-external-url-and-open-in-a-new-tab) – HDJEMAI May 11 '18 at 03:54
  • I want to open this file in new popup window. – david d May 11 '18 at 03:57
  • want to open in new popup window , this will open in new tab window.location.href="https://www.google.com"; it will not work for me – david d May 11 '18 at 03:58

3 Answers3

2

You must introduce the file in the assets of the Angular project. To access to the file you introduce 'assets/file2.pdf'.

window.open('assets/file2.pdf');

Don't use an absolute path, because if you deploy in a subdirectory doesn't work.

2

You should use Router.navigate Angular method:

import { Router } from '@angular/router';
    
constructor(
   private router: Router
) {}
    
open(){
   var URL = "file:///C:\data2.pdf";
   this.router.navigate(URL);
}
Dmitry S.
  • 1,544
  • 2
  • 13
  • 22
esther44
  • 53
  • 7
0

You should use a web server. Browser not allowed to getting client local file through JavaScript. Example:

var url = '//localhost:3000/data2.pdf';
window.open(url);

Here web server address localhost, and port 3000. As a web server can be for example Node JS, Apache, etc.

Abylay
  • 344
  • 2
  • 11
  • same issues not able to open the file. Not allowed to load local resource: file:///C:/docstore/doc7.1.pdf – david d May 11 '18 at 06:22
  • You can manually open a file in the browser as much as you like, but you can not go through the browser JavaScript, because it's not safe. You have to use HTTP instead of FILE. Read please about the web, how the web server works and how requests are processed. – Abylay May 11 '18 at 08:44