1

判断window.open是否被禁用或者阻止的方法

 1 year ago
source link: https://www.haorooms.com/post/windowopenfd
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

判断window.open是否被禁用或者阻止的方法

2023年7月7日 4734次浏览

在h5页面新开窗口,我们经常用window.open('haorooms.com','_blank'),但是这个方法在某些app内嵌h5中,或者某些浏览器中会阻止这个方法,那么有什么办法判断我们的open是否被阻止了呢?阻止之后我们有什么办法解决呢?今天聊聊解决方案。

其实window.open有个返回值的,在打不开或者被禁用的情况下面,window.open会返回null,利用这个特性,我们可以判断这个页面目前是都可以用window.open。

例如判断如下:

  var popup = window.open("haorooms.com", "_blank");
   //popup 为null,或者undefined即为阻止

利用这个特性,我们可以封装一个函数

 function isWindowOpenUrl(url) {
  let isBlocked = false
  try{
   let popup = window.open(url, "_blank");
    if (popup == null || typeof(popup) == "undefined") {
    // 弹出窗口被拦截,window.open被禁用
    isBlocked = true
    }
   }catch(e){
    isBlocked = true
   }
  if(isBlocked){// open被阻止,我们用location.href方式打开页面了
  location.href = url
   }
}

当然,你也可以仅判断是否阻止,代码如下:

function isWindowOpenEnabled() {
  var popup = window.open("", "_blank", "width=100,height=100");
  if (popup == null || typeof(popup) == "undefined") {
    // 弹出窗口被拦截,window.open被禁用
    return false;
  } else {
    // 弹出窗口被成功打开,window.open可用
    popup.close();
    return true;
  }
}

一个小的知识点,记录一下,供大家参考。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK