window.open无法使用谷歌浏览器?

时间:2013-03-03 21:19:03

标签: javascript google-chrome

我只想点击一个链接就打开2页,这就是我到目前为止所做的:

<a onclick="download()" href="?event=thanks&dl=<?php echo $_GET['dl']; ?>"><?php echo $linkname ?></a>

和Javascript函数:

function download() {
    newwindow=window.open('http://www.google.com','download','height=200,width=150');
    if (window.focus) {newwindow.focus()}
    return false;
}

上面的代码与FireFox和Safari完美配合,但无法使用Google Chrome打开新窗口。为什么是这样?我要感谢任何可以提供帮助的人。

2 个答案:

答案 0 :(得分:2)

<a>元素在HTML5中有一个下载属性,如此处所述,默认值为“”(空字符串)。

这意味着在onclick处理程序中下载=== this.download(这是onevent属性中的元素),因此该元素的download属性优于window的下载属性。

噢,真是个噩梦。您的函数不应命名为download()。将您的函数名称更改为download1()并将您的onclick更改为download1()

答案 1 :(得分:0)

您可以使用HTML5下载属性。此属性会告诉浏览器我们创建的虚拟链接仅供下载。它将从链接s href to file with name specified as download attribute的值下载文件。此功能适用于Chrome。 示例代码:

window.downloadFile = function(sUrl) {

    //If in Chrome or Safari - download via virtual link click
    if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
        //Creating new link node.
        var link = document.createElement('a');
        link.href = sUrl;

        if (link.download !== undefined){
            //Set HTML5 download attribute. This will prevent file from opening if supported.
            var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
            link.download = fileName;
        }

        //Dispatching click event.
        if (document.createEvent) {
            var e = document.createEvent('MouseEvents');
            e.initEvent('click' ,true ,true);
            link.dispatchEvent(e);
            return true;
        }
    }

    // Force file download (whether supported by server).
    var query = '?download';

    window.open(sUrl + query);
}

window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') &gt; -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') &gt; -1;
相关问题