Created
August 13, 2011 13:21
-
-
Save mathiasbynens/1143845 to your computer and use it in GitHub Desktop.
`unsafeWindow` polyfill (for use in user scripts)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ==UserScript== | |
| // @name Emulate `unsafeWindow` in browsers that don’t support it. | |
| // ==/UserScript== | |
| // http://mths.be/unsafewindow | |
| window.unsafeWindow || ( | |
| unsafeWindow = (function() { | |
| var el = document.createElement('p'); | |
| el.setAttribute('onclick', 'return window;'); | |
| return el.onclick(); | |
| }()) | |
| ); | |
| // You can now use `unsafeWindow`, ehm, safely. | |
| console.log(unsafeWindow); | |
| // If the current document uses a JavaScript library, you can use it in | |
| // your user script like this: | |
| console.log(unsafeWindow.jQuery); |
@mathiasbynens
Is it just me or did they fix it in the latest Canary?
It returns the safe window, not the unsafe one anymore.
Think there is a issue on Canary Build 28.0.1477.2
It seems like this no longer works in Chrome 29.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[Update]
Used
===instead of==andfinallyinstead of an emptycatch.[Original]
This snippet is helpful, and it works when used in Opera and Chrome. However, I find that GM's
unsafeWindowbecomes invalid if this is used in Firefox. Probably because it's not part of thewindowobject. In other words, I can't get it to work in Firefox.Here's my solution.
Chrome creates an anon function that wraps
windowas the argument forunsafeWindowso they are actually the same safe-window object. Opera will throw an error. Ifais false the fill is used, otherwise the realunsafeWindowis returned for Firefox.