防止浏览器返回按钮

Prevent browser back button

本文关键字:按钮 返回 浏览器      更新时间:2023-09-26

我一直在试图找出一种方法,当用户点击转义按钮,当用户点击浏览器后退按钮,它只是重定向到它取代的网页。我找到了工作得不错的代码:

function getAway() {
  // Get away right now
  window.open("http://weather.com", "_newtab");
  // Replace current site with another benign site
  window.location.replace('http://google.com');
  //Prevents back button from going back to website 
}
$(function() {
  $("#get-away").on("click", function(e) {
    getAway();
  });
  $("#get-away a").on("click", function(e) {
    // allow the (?) link to work
    e.stopPropagation();
  });
});
function checkStorage() {
  var myVar = sessionStorage.getItem("myVar");
  if (myVar != undefined) {
    window.history.forward();
  }
}
function check() {
  sessionStorage.setItem("myVar", "true");
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="keywords" content="Spanish Chat, Child Abuse Chat, Child Abuse Support, Child Abuse Discussion, Suvivor, chat, discussion, support, domestic violence, violencia domestica, abuso infantil, abuso de niño">
  <meta name="description" content="Moderated chat rooms for victims and survivors of child abuse and domestic violence.">
  <title>Yes ICAN: International Child Advocacy Network</title>
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="css/main.css">
  <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
  <!-- <script type="text/javascript">
      alert("SAFETY ALERT: If you are in danger, please use a safer computer, or call 911, your local hotline, or the U.S. National Domestic Violence Hotline at 1-800-799-7233 and TTY 1-800-787-3224. See more technology safety tips online.")
    </script>-->
  <script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-27303610-1']);
    _gaq.push(['_trackPageview']);
    (function() {
      var ga = document.createElement('script');
      ga.type = 'text/javascript';
      ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(ga, s);
    })();
  </script>
</head>
<body onLoad="initialize(); checkStorage();">
  <div id="wrapper">
    <!--Main Navigation Bar-->
    <nav class="navbar navbar-default">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="index.html">
            <img alt="site logo" id="navlogo" src="img/logo_short_sm.png" />
          </a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a data-toggle="tooltip" title="Home page" target="_blank" href="index.html">Home</a>
            </li>
            <li><a data-toggle="tooltip" title="Group Facilitated Chat Room" href="gethelp.html">Get Help</a>
            </li>
            <li><a data-toggle="tooltip" title="Message Board Community" href="community-rules.html">Community Forums</a>
            </li>
            <li><a data-toggle="tooltip" title="Learn More About Abuse" href="aboutabuse.html">About Abuse</a>
            </li>
            <li><a data-toggle="tooltip" title="Learn More About YesICAN" href="about-us.html">About Us</a>
            </li>
            <li><a data-toggle="tooltip" title="Opportunities to volunteer, donate, and get involved!" href="get-involved.html">Get Involved</a>
            </li>
          </ul>
          <!--Right side of navigation bar-->
          <ul class="nav navbar-nav navbar-right">
            <li>
              <div class="btn btn-lg btn-danger donate-nav"><a target="_blank" href="https://donatenow.networkforgood.org/yesican?code=Homepage">Donate <span class="glyphicon glyphicon-heart" aria-hidden="true"></span></a>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </nav>
    <!--END NAVIGATION-->
    <img id="banner" alt="home page banner" src="img/banner.jpg" />
    <div id="content">
      <section class="col-md-4">
      </section>
      <section class="col-md-8">
        <!--Left column content goes here-->
        <h2>Our Mission<small><br>Working World Wide to Stop the Silence and Cycle of Abuse</small></h2>
        <p>The International Child Advocacy Network, Inc. (YesICAN) is a leading global provider of online information for those who have issues around child abuse. It is our mission to work worldwide to break the silence and cycle of abuse. <strong><em>We</em> believe</strong> that
          child abuse could cease to exist if everyone had the capability to receive accurate, up-to-date information about abuse and then had the capacity to receive assistance and support to change.</p>
        <h2>How We Make a Difference</h2>
        <p>Our website provides information, statistics, and definitions of abuse. We also have the <a href="community-rules.html"><em>Yes</em>ICAN Community</a> where individuals who have questions regarding child abuse and domestic violence can join with
          others to discuss various concerns and ideas around these topics.</p>
        <p>The premier service of our organization is our <a href="chat-schedule.html">facilitated chat</a> groups. <strong>In these groups we offer an opportunity for abused children and adults to speak with others and to get council and support from trained facilitators.</strong> These
          facilitators have gone through a 60-hour training lead by a Licensed Therapist. To date, we have had over 44,000 participants in our chat rooms. We run specialized chat groups for teens, adult-survivors, victims of domestic violence, individuals
          who are in close relationship with abuse survivors and parents.</p>
        <h2>Our Current Focus</h2>
        <p>Our focus for now, is the development of an on-line parenting program. In this 6-8 week program, individuals will receive training in non-violent parenting. This training will include dynamics of both physical and emotional development, and appropriate
          discipline. In addition, each member of the program will have access to support groups where the topic of each weeks' training session will be discussed. During this time specific issues and concerns that come up for each participant will be
          shared in a safe and supportive environment.</p>
        <p>It is our hope that in the future, we will provide an international support forum, specifically targeting military personnel and their dependents that are based outside of the United States.</p>
      </section>
      <section class="col-md-4">
      </section>
      <section class="col-md-4" style="background-color:#eceef1; border-radius:10px;">
        <!--Right column content goes here-->
        <h2>Annual Bowling Event</h2>
        <a href="files/2015_Bowling%20Flyer_low_res.pdf" target="_blank">
          <div style="text-align:center; margin-top:30px;">
            <img src="img/2015_Bowling%20Flyer_th.jpg" alt="flyer thumbnail">
        </a>
        <br>
        <a href="https://donatenow.networkforgood.org/yic2015bowling" target="_blank">
          <button type="button" class="btn btn-lg btn-primary">Buy Tickets</button>
        </a>
        <br><small><a href="files/2015_Bowling%20Flyer_low_res.pdf" target="_blank">Click to see event details</a></small>
        </div>
        <br>
        <p>This Sunday <strong>June 14</strong>, come join your favorite <b>Star Wars</b> characters at the International Child Advocacy Network's <strong>Annual Bowling Fundraiser and Silent Auction!</strong>
        </p>
        <br>
        <h2>In Memorial</h2>
        <a href="memorial.html">
          <img alt="Memorial List" src="img/memorial_list.jpg" />
        </a>
        <p>We keep <a href="memorial.html">this list in honor of the children</a> who have died from the injuries infliected upon them as a result of child abuse.</p>
        <br>
        <h2>Missing Children<br><small>Alert Cases</small></h2>
        <section style="border: #cfd1d4 solid 1px; border-radius:2%; padding:5px;">
          <!-- start feedwind code -->
          <script type="text/javascript">
            document.write(''x3Cscript type="text/javascript" src="' + ('https:' == document.location.protocol ? 'https://' : 'http://') + 'feed.mikle.com/js/rssmikle.js">'x3C/script>');
          </script>
          <script type="text/javascript">
            (function() {
              var params = {
                rssmikle_url: "http://www.missingkids.com/missingkids/servlet/XmlServlet?act=rss&LanguageCountry=en_US&orgPrefix=NCMC",
                rssmikle_frame_width: "100%",
                rssmikle_frame_height: "400",
                frame_height_by_article: "0",
                rssmikle_target: "_blank",
                rssmikle_font: "Arial, Helvetica, sans-serif",
                rssmikle_font_size: "12",
                rssmikle_border: "off",
                responsive: "off",
                rssmikle_css_url: "",
                text_align: "left",
                text_align2: "left",
                corner: "off",
                scrollbar: "on",
                autoscroll: "off",
                scrolldirection: "up",
                scrollstep: "2",
                mcspeed: "20",
                sort: "Off",
                rssmikle_title: "off",
                rssmikle_title_sentence: "",
                rssmikle_title_link: "",
                rssmikle_title_bgcolor: "#FF0000",
                rssmikle_title_color: "#FFFFFF",
                rssmikle_title_bgimage: "",
                rssmikle_item_bgcolor: "#eceef1",
                rssmikle_item_bgimage: "",
                rssmikle_item_title_length: "55",
                rssmikle_item_title_color: "#0066FF",
                rssmikle_item_border_bottom: "on",
                rssmikle_item_description: "on",
                item_link: "off",
                rssmikle_item_description_length: "150",
                rssmikle_item_description_color: "#666666",
                rssmikle_item_date: "gl1",
                rssmikle_timezone: "Etc/GMT",
                datetime_format: "%b %e, %Y %l:%M:%S %p",
                item_description_style: "text+tn",
                item_thumbnail: "full",
                item_thumbnail_selection: "auto",
                article_num: "15",
                rssmikle_item_podcast: "off",
                keyword_inc: "",
                keyword_exc: ""
              };
              feedwind_show_widget_iframe(params);
            })();
          </script>
          <div style="font-size:10px; text-align:center; width:300px;"><a href="http://feed.mikle.com/" target="_blank" style="color:#CCCCCC;">RSS Feed Widget</a>
            <!--Please display the above link in your web page according to Terms of Service.-->
          </div>
          <!-- end feedwind code -->
        </section>
        <br>
      </section>
    </div>
    <div class="container" style="overflow-y: hidden;">
      <div class="modal fade" id="myModal">
        <div class="modal-dialog modal-md custom-height-modal">
          <div class="modal-content">
            <div class="modal-header" style="background-color:#d3d3d3">
              <button type="button" class="close" data-dismiss="modal">&times;</button>
              <h3 class="modal-title" style="text-align:center">Safety Warning</h3>
            </div>
            <div class="modal-body">
              <p style="text-align:center">Your computer can be monitored by others. For your safety, consider using a public computer or a friend’s computer. If you are in danger, please call 911, your local hotline, or the U.S. National Domestic Violence Hotline at<a href="tel:+1.800.799.7233"
                class="call" onClick="return probablyPhone;"> +1-800-799-7233</a> and
                <br>TTY <a href="tel:+1.800.787.3224" class="call" onClick="return probablyPhone;">+1-800-787-3224</a>.</p>
              <p style="text-align:center">To learn more how to computer safety, click the following link:
                <br><a href="internet-safety-tips.html">Internet Safety Tips</a>
                <br>
              </p>
              <!--Wording can be better just for the meantime-->
              <p style="text-align:center">If you are not safe, click the following button:
                <br><span class="btn btn-lg btn-danger" id="get-away" id="del_cookie">Escape Button</span>
                </br>
              </p>
            </div>
            <div class="modal-footer">
              <p class="text-center"><a href="" class="btn btn-default" class="btn pull-middle" data-dismiss="modal">Close</a>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--End of Modal container-->
    <!--<div class="container">
                <section class="col-md-3">
                  <div class="list-group" id="sidebar">
                    <a href="#" class="list-group-item">
                      Link 1
                    </a>
                  </div>
              </section>
            </div>-->
  </div>
  <!--End wrapper-->
  <footer>
    <div id="footer-right">
      <ul>
        <li>ABOUT US</li>
        <li><a href="contact.html">Contact Us</a>
        </li>
        <li><a href="faq.html">FAQ's</a>
        </li>
        <li><a href="sitemap.html">Site Map</a>
        </li>
      </ul>
      <ul>
        <li>SUPPORT OUR CAUSE</li>
        <li><a href="https://donatenow.networkforgood.org/yesican?code=Homepage" target="_blank">Donate</a>
        </li>
        <li><a href="volunteer.html">Volunteer</a>
        </li>
        <li><a href="fundraiser.html">Fundraising Events</a>
        </li>
      </ul>
      <ul>
        <li>FOLLOW US</li>
        <li>
          <a target="_blank" href="http://ww.facebook.com/yesicanorg">
            <img src="img/social/facebook-icon.png" alt="Facebook Logo" class="social-icon">
          </a>
          <a target="_blank" href="http://www.instagram.com/childadvocacynetwork">
            <img src="img/social/instagram-icon.png" alt="Instagram Logo" class="social-icon">
          </a>
          <a target="_blank" href="http://twitter.com/YesICANorg">
            <img src="img/social/twitter-icon.png" alt="Twitter Logo" class="social-icon" />
          </a>
          <a target="_blank" href="http://www.pinterest.com/Yesicanorg">
            <img src="img/social/pinterest-icon.png" alt="Pinterest Logo" class="social-icon" />
          </a>
          <a target="_blank" href="http://www.youtube.com/childadvocacynetwork">
            <img src="img/social/youtube-icon.png" alt="YouTube Logo" class="social-icon" />
          </a>
        </li>
      </ul>
    </div>
    <div id="footer-left">
      <p id="footer-slogan">BREAK THE <strong>SILENCE</strong> 
        <br>AND <strong>CYCLE</strong> OF ABUSE</p>
      <p id="copyright">Copyright&copy; 2015 International Child Advocacy Network</p>
    </div>
  </footer>
  <!-- Bootstrap core JavaScript placed at the end of the document so the pages load faster -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
  <!--<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>-->
  <script src="js/bootstrap.min.js"></script>
  <script src="js/escape-button.js"></script>
  <script src="js/checkStorage.js"></script>
  <!--Testing to see if it works-->
  <!--<script>
            $(document).ready(function() {
                 if ($.cookie('pop') == null) {
                     $('#myModal').modal('show');
                     $.cookie('pop', '1');
                  }
             });
           </script>-->
  <!--Works fine-->
  <script>
    $(function() {
      $('#myModal').modal('show');
    });
  </script>
  <script>
    var probablyPhone = ((/iphone|android|ie|blackberry|fennec/).test(navigator.userAgent.toLowerCase()) && 'ontouchstart' in document.documentElement);
    function initialize() {
      (function($) {
        $('.call').css("text-decoration", "none");
        $('.call').css("color", "black");
        $('.call').css("cursor", "default");
      })(jQuery);
    }
  </script>
  <script>
    function checkStorage() {
      var myVar = sessionStorage.getItem("myVar");
      if (myVar != undefined) {
        window.history.forward();
      }
    }
    function check() {
      sessionStorage.setItem("myVar", "true");
    }
  </script>
</body>
</html>

这就是我所做的,我添加了html代码,转义按钮代码和你给我看的代码

如果在按下"Escape"按钮后,你希望用户重定向到其他页面,而不希望他/她即使在浏览器中按下"back"键也会返回,那么你可以这样做。

在body标签中包含onload事件,

<body onload="checkStorage()">
    <!--You body content-->
</body>
现在使用下面的脚本,
    <script type="text/javascript">
            function checkStorage() {
                var myVar = sessionStorage.getItem("myVar");
                if (myVar != undefined) {
                    window.history.forward();
                }
            }
            function check() {
                sessionStorage.setItem("myVar", "true");
                //the URL you want the user to get redirected to when
                //they press "Escape" button
                window.location.replace("http://www.saumilsoni.me");
            }
        </script>

UPDATE:如果你已经在onload上调用了一些函数,你可以使用回调函数的概念,因为在onload中定义多个函数在某些浏览器中可能会有问题。这是你可以做的,

<body onload="checkStorage()">
    <!--You body content-->
</body>
<script>
    function checkStorage(){
        var myVar = sessionStorage.getItem("myVar");
        if (myVar != undefined) {
            window.history.forward();
        }else{
            //call the function here that you previously called onload
            yourFunction();
        }
    }
</script>

我恳请您不要破坏后退按钮。从20世纪90年代开始,我们就知道打破后退键是个坏主意。

用户期望他们的浏览器如何工作,当你故意打破一些正常的工作方式,你会挫败,激怒,甚至可能激怒他们。如果您的网站以不可预测或非标准的方式运行,许多人将拒绝使用您的网站。不小心让网站变得难以使用是很容易的,故意让你的网站变得难以使用是一个坏主意。