Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
confidence68 opened this issue Jul 9, 2023 · 0 comments
Open

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

confidence68 opened this issue Jul 9, 2023 · 0 comments

Comments

@confidence68
Copy link
Owner

背景

在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;
  }
}

小结

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant