これは、独自のドメインの特定のパスと外部リンクをブロックできるようにする 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