views:

193

answers:

1

okay i have a question...

i need an message script that only will come up when people are really leaving the current webpage so not the current website...

so actualli when people are leaving the website entirelly the message will come up, they need to press the ok button to stay at the current page and cancel to leave the entire website..

the script may not run when people are actually stay on the website or when the click on internal links/pages..

does that make sence/? and can it be done? who know such code?

+1  A: 

Check out this very basic example solution. It sets the onbeforeunload handler but then removes it if the user clicks an internal link. Below is a generic version of the code from the example solution.

HTML:

<a href="internal_link.html">internal link</a>
<a href="http://www.example.com"&gt;external link</a>

JS (uses jQuery):

window.onbeforeunload = function(){
    return "Are you sure you want to leave our website?";
}
$(function(){
    $('a').click(function(){
        if (this.href.match(location.host)) { //this test could be improved upon
            //alert('Please continue on to our site.');
            window.onbeforeunload = null;
        } else {
            //alert('You are about to leave our website.');
        }
    });
});
Adam
so what will be the total code iclude the query string etc? and i dont understand the internal link part? as i cannot change our internal links which are automativly generated by our shopping cart
tumtummetjes
and offcourse the html tags body part etc
tumtummetjes
The line `<a href="internal_link.html">internal link</a>` is simply an example of a link which will have the same domain name as `location.host`. Any link which is "internal" to your website (meaning it doesn't link to a different domain) should cause the `if` statement `this.href.match(location.host)` to return `true`, causing the `onbeforeunload` handler to be removed, thus preventing preventing the message `"Are you sure you want to leave our website?"` message from popping up. [... comment continued below ...]
Adam
[... comment continued from above ...]Links like the second one (`<a href="http://www.example.com">external link</a>`) *will* cause the message to pop up (as you desired) since they will have a different domain from `location.host`. (Sorry if there was confusion from forgetting the `onbeforeunload` handler in my first post. Please refer to the example solution http://polymath.mit.edu/projects/test/stackoverflow/onbeforeunload_external_links.html if you have any other questions.)
Adam