javascriptpopup

How to tell if a popup will get blocked


I appreciate how browsers work when deciding whether a window.open() was triggered by a click, as in, it's only allowed when it came from a real element click event.

I want to write the same logic myself, how do I do that?

Say I have any JS function, called potentially anywhere and everywhere from the rest of my application, sometimes with a click event handler at the start of the callstack and some times not. How can I know this inside my method, without explicitly passing information about the start of the stack (click vs not) all the way around my application?

function iNeedToKnowIfStackFrame0WasAClickEventListener() {
  var wasAClick = ???;
  if(wasAClick)
    window.open(...);
  else
    something.else();
}

Solution

  • You can get the event information using this.event.type. You can either pass the event into the function like so:

    function iNeedToKnowIfStackFrame0WasAClickEventListener(event) {   
        var wasAClick = event.type == "click";    
        if(wasAClick)
            window.open(...);   
        else
            something.else(); 
    }
    

    or you can get the event off this

    function iNeedToKnowIfStackFrame0WasAClickEventListener() {   
        var wasAClick = this.event.type == "click";    
        if(wasAClick)
            window.open(...);   
        else
            something.else(); 
    }