1. 程式人生 > >回撥函式中window.open()被攔截

回撥函式中window.open()被攔截

在回撥函式中window.open預設是會被攔截的,因為瀏覽器判斷它不是使用者自己開啟的,存在安全風險,所以可以偽造一個使用者點選事件來避開,程式碼如下:

function newWindow(url, id) { 
	var a = document.createElement('a'); 
	a.setAttribute('href', url); 
	a.setAttribute('target', '_blank');
	a.setAttribute('id', id); 
	if(!document.getElementById(id)) { 
	document.body.appendChild(a);
	} 
	a.click(); 
}
使用時直接將連結傳入url就行,id可傳可不傳。