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.

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top