zoukankan      html  css  js  c++  java
  • 防止浏览器拦截的新窗口打开链接方案

    背景

      当前的浏览器为了保证用户体验,在很多场合下禁止了window.open打开新窗口,下面就给出一些方案,最大程度上的实现新窗口打开一个链接。

    方案

    //打开新链接方法实现
    function windowOpen(){
        var a = document.createElement("a");
        a.setAttribute("href", url);
        if(target == null){
            target = '';
        }
        a.setAttribute("target", target);
        document.body.appendChild(a);
        if(a.click){
            a.click();
        }else{
            try{
                var evt = document.createEvent('Event');
                a.initEvent('click', true, true);
                a.dispatchEvent(evt);
            }catch(e){
                window.open(url);
            }
        }
        document.body.removeChild(a);
    }
    
    //新窗口打开
    windowOpen('http://niu.xunlei.com/', '_blank');
    //当前窗口打开 
    windowOpen('http://niu.xunlei.com/', '_self');

    思路

      其实做法很简单,首先模拟A标签点击打开新窗口,若失败再直接调用window.open方法。

    问题

      目前无法在异步的情况下调用该方法。如下:

    //以下做法将得不到期望的结果,会被浏览器阻止
    $.get("http://www.a.com/ajax",function(){
        windowOpen('http://niu.xunlei.com/', '_blank');
    });
    本文为原创文章,转载请注明出处:http://www.cnblogs.com/zernmal/
  • 相关阅读:
    java跳过构造方法新建对象
    java实现类似qq的窗口对聊
    NoSql的产生
    C语言跳出循环
    C语言for循环
    C语言while语句
    C语言条件运算符
    C语言switch语句
    C语言逻辑运算符
    C语言关系运算符
  • 原文地址:https://www.cnblogs.com/zernmal/p/3909575.html
Copyright © 2011-2022 走看看