user

Shilpa

2 Mar 2022

How to call event handler onload for Angular application?

Angular

I want to open a window containing user authorization form details. I want to do this by checking window location, to do so the event handler not call on every event.  I am not able to overwrite event handlers.

Why the event is not triggering? what could be the alternative way to intercept the Authorization form result?

My code:

import { Inject, Injectable } from '@angular/core';

// ... other imports will be go here. //

@Injectable({
 providedIn: 'root'
})
export class UserWindowService {

 constructor(@Inject(WINDOW) public window: Window) {} // here WINDOW is imported from InjectionToken<Window>

 openUserWindow(): void {
 let windowObj = this.window.open('//localhost:4200/verify', '_blank');
 let evntHandler= function() {
 console.log(windowObj!.location);
 };
 //Below order of events should execute one by one, one after one.
 windowObj!.onload = evntHandler;
 windowObj!.addEventListener('load', evntHandler);
 windowObj!.addEventListener('onload', evntHandler);
 windowObj!.document.onload = evntHandler;
 windowObj!.onhashchange = evntHandler;
 windowObj!.addEventListener('hashchange', evntHandler, false);
 }
}

Comments

Rakshit

5 Mar 2022

Best Answer

best answer

When you call “window.open()”, it seems like, your window may be blocked by a popup blocker. Chrome Firefox and other giants in browsers - all are using one common thing, like popup blocker to prevent loading of hundreds of tabs using javascript - malscript functionality.

 

You should check if the “window” variable exists or not.

...
if(this.window){
//PUT Your code here ...
}
...

when you use exclamation mark, “windowObj!.onload”, you are forcing to open a window.

In such case, window!.addEventListener() might not work (exclamation will fail) if window does not exist.

Remember: You can't use load listener to your window instance when you use, window.open()

Shilpa

6 Mar 2022

github

Yes popup blocker is issue, if I am allowing popup from the top of chrome browser, it works fine! Thanks for sharing knowledge.

© 2024 Copyrights reserved for web-brackets.com