我想在jQuery中建立一個非現場通知功能。該腳本首先檢查鏈接是否是外部鏈接,然後針對數據庫表項檢查異常。如果鏈接是外部鏈接而不是例外列表,請將訪問者發送到通知頁面。如果它是例外列表上的外部鏈接,則在沒有通知頁面的情況下在新窗口中打開鏈接。如何避免JavaScript`window.open`觸發彈出窗口警報
我正在使用jQuery $.post
調用將鏈接信息發送到php腳本,該腳本檢索異常並返回yes或no,以便它需要轉到通知屏幕。下面的代碼:
$('a').click(function(){
var url =$(this).attr('href');
if(url !== '#'){
// ignore links that don't 'go' anywhere
if($(this).hasClass('alerted')){
// .alerted is used on the notification page to show the user's already been notified & prevents an infinite loop of notifications.
window.open(url);
return false;
}else if(url.substr(0,4) !='http'){
// check that the url isn't an internal link ('/page.php' for example)
return true;
}
// ajax script to check url is external and is there an exception. Returns as json object:
// link: link
// notify: true/false
$.post("/scripts/form_process.php", { action : 'offsite', link: url}, function(data){
if(data.notify == true){
// if visitors should be notified, redirect to the following link:
window.location= '/leaving-site?link='+encodeURIComponent(data.link);
return false;
}else{
// if the link is in the exception list, don't notify but do open the link in a new window:
window.open(data.link);
}
});
return false;
}
});
這只是工作的罰款,只要window.open(url)
命令是$.post
成功函數裏,瀏覽器處理它像一個彈出式的,而不是作爲一種天然的聯繫。據我所知,在ajax
調用中使用window.open
時,這似乎是個問題。當我在這裏使用它時:
if($(this).hasClass('alerted')){
// .alerted is used on the notification page to show the user's already been notified & prevents an infinite loop of notifications.
window.open(url);
return false;
}
我沒有得到彈出式窗口攔截器。
我不能硬編碼例外列表,我必須檢查每一個鏈接 - 我不能假設一個類將被添加到需要通知的鏈接例如。
如何打開新選項卡中的外部鏈接並避免此代碼中的彈出窗口阻止程序?
你是對的,只要它落在那個以外點擊「線程」,它將被視爲一個未經請求的彈出窗口。我們在這裏談了很多鏈接嗎?在頁面加載時,您可以在用戶查看當前內容的同時抓取外部鏈接並在後臺驗證它們嗎? –
彈出窗口攔截器允許基於用戶的直接/實際點擊是否觸發代碼調用window.open。一個Ajax響應處理程序顯然不是這些東西之一。它不是由點擊觸發的,而是由一些網絡活動觸發的。這個網絡活動是否由點擊引起並不重要 - 點擊鏈接和觸發成功處理程序之間沒有直接聯繫。因此被阻止。 –
@Brad Cristie - 這個網站是客戶端可編輯的,所以網站上的每個鏈接都必須被檢查,所以可能有很多鏈接。儘管 – TH1981