0

I'm trying to get the only last visited page by the user, it should update on every page. I tried to save the URL in session cookie from there I'm retrieving the last visited page.

This is my code:

function getSecondCookie(cSname) {
    var name = cSname + "=";
    var ca = document.cookie.split(';');
    for ( var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0)
            return c.substring(name.length, c.length);
    }
    return "";
}

function checkHistory(targetId) {
    var history = getSecondCookie("history");
    var htmlContent = '';

    if (history != "") {
        var insert = true;
        var sp = history.toString().split(",");
        for ( var i = sp.length - 1; i >= 0; i--) {
            htmlContent += '<a class="previous_url"  href="'
                    + sp[i]
                    + '">'
                    + sp[i].substring(sp[i].lastIndexOf('/') + 1) + '</a><br>';
            if (sp[i] == document.URL) {
                insert = false;
            }
            document.getElementById(targetId).innerHTML = htmlContent;
            console.log(sp[i]);
        }
        if (insert) {
            sp.push(document.URL);
        }
        setSecondCookie("history", sp.toString(), 30);
    } else {
        var stack = new Array();
        stack.push(document.URL);
        setSecondCookie("history", stack.toString(), 30);
    }
}

This is working fine how it has to. At the moment it is showing like this:

https://www.example.com,https://www.example.com/about.html

and so on.

But I want here show only last element from an array. How can I do this?

3

2 Answers 2

6
let lastItem = array[array.length-1];
Sign up to request clarification or add additional context in comments.

Comments

0

You can also do:

const last = array.slice(-1)[0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.