I'm writing a Greasemonkey script that I'm trying to use in Chrome and Firefox. I know you can't use unsafewindow
in Chrome like you can in Firefox, so I've been attempting to use jS-uris like in the answer for: Greasemonkey, Chrome and unsafeWindow.foo().
when I try the following:
location.assign("javascript:var tutu = 'oscar';");
location.assign("alert('1:' + tutu);");
alert('2:' + tutu);
I receive an error showing that "tutu" is undefined. Obviously what I'm not understanding is the scope of these variables. I need to make global functions and variables for what I'm working on. What am I not doing correctly?
EDIT: Actually I think the problem isn't what I'm trying (unless it is, in which case please tell me) but the page I'm writing the script for looks is messing with URLS to keep them from going to anything but a relative URI.
In Chrome, there is a delay after the
location.assign
calls (they may run in separate threads), so thetutu
var isn't defined when thealert()
fires and the whole code throws an exception. (Also, as trinity said, thealert
needs to be prefaced withjavascript:
.)You could use a timer like so:
But, I think you'll agree that's a spot of bother.
Trying to do page-scope javascript with
location.assign
will get cumbersome for all but the shortest/simplest code.Set, reset, and/or run lots of page-scope javascript using Script Injection: