问题
I have made a userscript for a forum that resizes images. It works great, except for after posting or editing where it redirects, where onreadystatechange
does not fire in Google Chrome.
When viewing a thread, EG SomeSite/forums.php?action=viewtopic&topicid=205362, the userscript works.
After editing/posting, EG SomeSite/forums.php?action=viewtopic&topicid=205362&page=p4976670#4976670, the userscript doesn't work.
The problem lies with this code:
document.onreadystatechange = function () {
if (document.readyState == "complete") {
//Call function
}};
I wait for all resources to be loaded, because the resizing is inconsistent otherwise on pages with many images.
The script works perfectly in Firefox with Greasemonkey.
Any idea why onreadystatechange
does not fire on Chrome after a redirect? Is there a better way to wait for resources to have been loaded?
回答1:
You didn't state whether you use the @run-at
parameter but, by default, Chrome userscripts are somewhat erratic about when they fire.
That means that sometimes a userscript will fire before the onload
event and sometimes it will fire after (by default). If it's after the onload
event, then onreadystatechange
won't trigger.
To adapt to this behavior, either add // @run-at document-end
to the metadata block, or replace that code snippet with:
window.addEventListener ("load", YourMainFunction, false);
if (document.readyState == "complete") {
YourMainFunction ();
}
function YourMainFunction {
// DO ALL YOUR STUFF HERE...
}
In the latter case, YourMainFunction()
will either wait for the load event (same as readyState == "complete"
) or fire immediately if the event has already passed. YourMainFunction()
will only run once in either case.
来源:https://stackoverflow.com/questions/11594493/onreadystatechange-not-not-working-after-header-redirection-in-chrome