window.open is blocked by popupblocker

I have this code (based on what I could find on the internet about this problem):

<script>
  var newwindow = null;
  var btn = $('#btnCED');
  if (btn.length == 0) { 
    btn = document.createElement('button');
    btn.id = 'btnCED';
    var body = document. getElementsByTagName('body')[0];
    body.appendChild(btn);
    $('#btnCED').css('display','none');
    $(document).on('click', '#btnCED', function(e) {
      if (newwindow != null && !newwindows.closed) {
        setTimeout(function() {
          newwindow.location = 'https://google.com';
        }, 1000);
      }
    });
  }
  $(document).ready(function() {
    newwindow = window.open('');
    setTimeout(function() {
      $('#btnCED').trigger('click');
    }, 1000);
  });
</script>

When the page is ready, the button has been placed and the click event fires. But newwindow remains null because the browser blocks it already.

Almost every post I have read using a variable to store the window and using a button to get a click event is mentioned as the solution.

The window.open line is now in the ready part but I have also tried it when it was inside the click event and inside the settimeout function in the click event.

Then why is this not working??

Answer

There are two reasons it isn’t working:

  1. The window.open() call is not triggered by a button click. You have that directly in the ready event handler.
  2. Only real button clicks count. Programmatically generated ones don’t. (Allowing programmatic clicks would defeat the object, which is to allow new windows only in response to user interactions).