1

I have following piece of code in my ngOnInit event.

  ngOnInit()
  {
    let Url = window.location.href.trim().toLocaleLowerCase();
    if (Url.startsWith("https://"))
    {
      console.log('HTTPS');
      let NewUrl = Url.replace("https://", "http://");
      this.document.location.href = NewUrl;
    }
  }

My aim is that if Url is having HTTPS then I need to redirect to same Url but with HTTP. But this piece of code is not working even though code comes to the HTTPS block. No error or warning is shown either. I already have tried using

  1. document.location.href
  2. location.href
  3. this.router.navigateByUrl
  4. Injecting DOCUMENT and using this.document.location.href

I am using

  • Angular: 7.1.0
  • Angular CLI: 7.1.4
  • Node: 10.15.3
  • OS: win32 x64
  • @angular/router: 7.1.4

How to achieve my purpose?

Thanks in advance,

Maksat Rahmanov
  • 377
  • 3
  • 10
Gulfam
  • 558
  • 6
  • 27
  • check this out https://developer.mozilla.org/en-US/docs/Web/API/Location/href (where they tell: "If you want redirection, use location.replace()") or try way with window.open(NewUrl, '_self') – Maksat Rahmanov Nov 26 '21 at 07:33
  • 1
    Try the responses here: https://stackoverflow.com/q/4723213/6513921 – ruth Nov 26 '21 at 07:40

2 Answers2

1

I had to do this in IIS. No solution worked n JavaScript.

Gulfam
  • 558
  • 6
  • 27
0

you should consider a bit cleaner if condition -

if (window.location.protocol === 'https:') {
    const correctProtocolUrl = window.location.href.trim().toLocaleLowerCase().replace('https://', 'http://');
    window.location.href = correctProtocolUrl;
}

I've tested this in angular 13, but expecting similar behaviour since angular should not do anything with window.

But if you have backend solution I think that is the best way this can be done.

Nomik
  • 170
  • 2
  • 5