Pregunta

I am trying to create a basic script in Tampermonkey. I would like to visit one URL, wait 1 second and then visit another:

$(document).ready(function() {
    document.location.href = 'http://www.google.com';
    setTimeout(doStuff ,1000);
});

function doStuff(){
    document.location.href = 'http://www.stackoverflow.com';
}

The function doStuff does not appear to be called ever. Whenever I run the script, I get redirected to google.com, but then not to stackoverflow.com.

¿Fue útil?

Solución

A JavaScript execution environment only lasts for the lifetime of the page.

When you set location.href you leave the page, so any pending JavaScript won't run because its environment no longer exists.

Otros consejos

You could use iframes to accomplish your goal This will do what you are looking for:

<body>
  <iframe style='width: 100%; height: 100%;' id='myframe' />
</body>

Then change your document.location.href to document.getElementById('myframe').src = 'URL HERE';

This way the user will never technically leave your screen, and you can change which page they are viewing.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top