3

これは重複している可能性が高いことを認識していますが、1日グーグル/SOを行ってきましたが、満足のいく答えが見つかりません. SOにすでに回答がある場合は、そこに送ってください。

Gmail と同じように、サイトを終了することを確認する終了メッセージ ポップアップを表示することを主張するクライアントがいます。(私はすでにそれに反論しようとしました。彼は動かないので、それがどのように悪い習慣であるかについてのコメントはありません。)

私はこのコードを見つけました:

<script>
    window.onbeforeunload = function() {
        return 'Are you sure you want to exit?';
    }
<script>

しかし、ページのリロード、ナビゲーションのクリックなど、何をしても実行されます。

ユーザーがタブ/ブラウザを閉じたときにメッセージを表示したいだけです。私が見逃しているのは単純なものだと思いますが、私は Javascript の専門家ではありません。

どんな助けでも大歓迎です。

ありがとう

編集

これがかなりうまく機能しているものです。ありがとうございます!

var isLeavingSite = true;

//This would be called on each link/button click that navigates
$('a, input[type="submit"]').click(function(){
    isLeavingSite = false;
});

window.onbeforeunload = function() {
    if(isLeavingSite)
    return 'Are you sure you want to exit?';
}
4

3 に答える 3

1

Though it could be a fair amount of work (depending on how your site is written), you could do something like this (pseudo-code):

var isLeavingSite = true;

//This would be called on each link/button click that navigates
function GlobalLinkHandler()
{
    isLeavingSite = false;
}

window.onbeforeunload = function() {
    if(isLeavingSite)
    return 'Are you sure you want to exit?';
}

If you're using jQuery, you can use the code below to flip the isLeavingSite flag:

$('a, input[type="submit"]').click(function(){ isLeavingSite = false; });
于 2011-11-18T16:51:01.983 に答える
1

What'll have to do is make use a variable that you set if any link is clicked on the site, then inside the onbeforeunload event check if that variable is set meaning they clicked a link or not set meaning they're closing the tab.

You can also use that variable to simple set the href of the link; that will allow you to then check what link they clicked on inside the onbeforeunload event and allow you to check if they're clicking on a link to go to another page on your site or clicking on an external link to another site.

于 2011-11-18T16:51:56.650 に答える
0

jQueryを使用している場合は、終了する前にこれを確認してください

于 2011-11-18T16:50:20.430 に答える