2013-03-03 368 views
1

我试图打开2页的链接的点击,这是我到目前为止有:window.open不适用于谷歌浏览器?

<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打开新窗口。为什么是这样?感谢任何能够帮助的人。

+0

见[1](http://stackoverflow.com/questions/2572333/google-chrome-window-open-workaround)和[2](http://stackoverflow.com/问题/ 4994063 /设置该页面的标题 - 铬窗口打开) – 2013-03-03 21:21:21

+0

在Chrome的检查器中检查控制台。这会通知你任何错误。 – 2013-03-03 21:21:29

+0

它可能不喜欢上面代码中隐含的全局变量'newwindow',你是否明确地将它声明在脚本中其他地方的更高范围?如果不是,并且不需要保留对创建窗口的引用,那么只需在'var'前加上JS函数的第一行即可。 – DaveRandom 2013-03-03 21:30:03

回答

2

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

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

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

+0

工作得很好。谢谢! – 2013-03-03 21:33:27

+0

对不起,为什么这会根据上面的代码产生任何不同? – DaveRandom 2013-03-03 21:33:34

+0

我认为chrome有自己的默认功能下载,正因为如此,上述代码不起作用,因为用户试图调用下载功能 – MIIB 2013-03-03 21:34:35

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; 
相关问题