下面是Ryan回答的改進,它允許您阻止自己的域以及外部鏈接的特定路徑。
它會單獨檢查主機和路徑 - 因此您可以阻止所有不屬於您自己的域的鏈接,以及您自己的域中的特定路徑。
如果用戶點擊被阻止的鏈接,「request_confirmation」功能會在允許導航離開當前頁面之前向用戶請求確認。
我已將邏輯分解爲多個功能,因此您可以輕鬆修改它。
$('body').on('click', 'a', function(e){
return (should_link_be_blocked($(this).attr('href')))? request_confirmation() : true;
});
function should_link_be_blocked(link){
var url = new URL(link);
return should_host_be_blocked(url.hostname) || should_path_be_blocked(url.pathname);
}
function should_host_be_blocked(host){
return !(host.match(/([a-z0-9]+\.)?example.com/));
}
function should_path_be_blocked(path){
var not_allowed = ['/block_me.html', '/block_another.html'];
var block = false;
not_allowed.forEach(function(n_a){
block = (path == n_a)? true : block;
});
return block;
}
function request_confirmation(){
return confirm('This is an external link. Are you sure you want to leave?');
}
這裏工作的是一個醜陋的例子:http://codepen.io/anon/pen/Gjagi
所以我會把其中mydomain.com是上面顯示的網站的域名?你可以給我一個例子,我將如何添加另一個域到該JavaScript?謝謝。 – Lonnie 2014-09-04 21:39:22
@Lonnie這是正確的,只需將其替換爲您的域。我更新了代碼以顯示多個域。 – Ryan 2014-09-04 21:41:35
我用這個替換了原來的腳本並添加了兩個域,它不起作用。彈出窗口根本不顯示任何外部鏈接。 – Lonnie 2014-09-04 21:58:51