erol_smsr
erol_smsr

Reputation: 1496

document.referrer gives an incorrect value

I use document.referrer to see if a user has added a new message on my application. The page where the messages are shown is called 'messages.php' and the script that handles adding messages is called 'add_message.php'.

I want to create an effect on the last added message, but only if the user has just added the message. To see if the last message was just added and wasn't there before, I need to see if the user's last visited page was 'add_message.php'.

This is the code I use to detect the last visited URL with an if statement to check if that's the case:

var prevURL = document.referrer;
var newMessageURL = 'add_message.php';
if(prevURL.indexOf(newMessageURL) > -1) {
    alert(prevURL);
}   

The problem is that when I add a message, the script 'add_message.php' is called (via form action), however, document.referrer returns 'messages.php' as the last visited page, but it should be 'add_message.php', because that's where I come back from when I add a new message.

How can I get document.referrer to return 'add_message.php' when I add a message?

In the 'add_message.php' I use

header('Location: ' . $_SERVER['HTTP_REFERER']);

Does this cause the issue?

Upvotes: 0

Views: 1083

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Referrers are unreliable at best, especially as browsers come with the option to spoof or hide it completely. In this case, because it's a redirect, the "in-between" page doesn't get counted as the last page you visited.

That said, since you're using PHP, there's another way:

As part of your add_message.php file, add this:

// assuming you already have session_start() somewhere above
$_SESSION['just_added_a_message'] = true;

Then, where you have your JavaScript now, replace it with PHP:

<?php
if( !empty($_SESSION['just_added_a_message'])) {
    ?>
    <script>alert("Ohai there!");</script>
    <?php
    unset($_SESSION['just_added_a_message']);
}
?>

I use this technique myself to show a confirmation "You sent a Personal Message to X" message when the user has been redirected back to their Inbox after sending.

Upvotes: 1

Related Questions