简体   繁体   English

window.open 被 popupblocker 阻止

[英]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.但是newwindow仍然为空,因为浏览器已经阻止了它。

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. window.open 行现在处于就绪部分,但我也尝试过它在 click 事件中和 click 事件中的 settimeout 函数中。

Then why is this not working??那为什么这不起作用?

There are two reasons it isn't working:它不起作用有两个原因:

  1. The window.open() call is not triggered by a button click. window.open()调用不是由单击按钮触发的。 You have that directly in the ready event handler.您可以直接在ready事件处理程序中使用它。
  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). (允许程序化点击会破坏对象,即只允许新窗口响应用户交互)。

我更改了页面,因此用户现在必须按下一个按钮才能显示新窗口/选项卡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM