5

I'm new to JavaScript and trying to get this Tampermonkey script working. The scripts works just fine when it collects data from one page. However, I now want it to collect the data as before, but then move on to another page and continue the data collecting.

My code:

$(document).ready(function() {
    $("#getData").click(function() {
        // Part 1. Collect data and move on
        window.location.href = goToURL;
        // Part 2. Collect more data when the page has fully loaded
    });
});

I have tired to put Part 2 of the code inside:

setTimeout(function() {
}, 5000);

and

window.onload = function(){
};

But I cannot get the code to work, it either executes before the page has loaded, or seemingly not at all. What am I missing?

3
  • 2
    New page means new instance of the code. Anything stored in memory is lost. Is new page on same domain? Commented Aug 10, 2017 at 7:48
  • Even when executing the code via Tampermonkey? Yes, it's on the same domain. Commented Aug 10, 2017 at 7:59
  • Yes...Tampermonkey runs new instance every page load. @Vladimir suggestion of localStorage is simple way to do it. Or use a cloud storage Commented Aug 10, 2017 at 8:00

1 Answer 1

1

When you change page with location.href, your JS is reloaded. So you need a way to store data between page changing. I suggest to use LocalStorage Your code would look like:

function storeState(state){
    localStorage.setItem('state', state);
}

function loadState(state){
    return localStorage.getItem('state');
}

$(document).ready(function() {
    var state = getState();
    $("#getData").click(function() {
        // Collect data and put it into state
        storeState(/* your collected state*/)
        window.location.href = goToURL;
    });
});

Notice that you have to do some serialize/deserialize stuff because localStorage only save strings Also as mentioned @charlietfl if you have different domains it will cause additional difficults

Sign up to request clarification or add additional context in comments.

1 Comment

Should move comment for "Part 2" since won't be in the click handler

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.