I am writing a bookmarklet which performs some function on a page. As part of this function I need to use getElementsByClassName. However, during testing I found that several websites have redefined getElementsByClassName to a custom method. Presumably this was done in order to support getElementsByClassName in all browsers.
The implementation of custom getElementsByClassName is a bit sloppy and fails for several of my use cases. Is there any way I could get the original definition of getElementsByClassName?
In the chrome javascript console: getElementsByClassName points to a native function. Is there a way to access this native function, now that getElementsByClassName has been redefined?
There is a solution, but it is not robust. See the disclaimer at the bottom.
If you open a new window you will have access to its unmodified methods. I can think of two ways to open a new window: using
window.open, and in an iframe. The iframe is less obtrusive because it won’t distract the user by opening new browser windows or triggering pop-up blockers.Some browsers won’t like removing the iframe. If you want this to work in Safari or Firefox, delete the removeChild line. Next, you will want to get the getElementsByClassName method from the new window.
This is pretty much cross-browser, except that IE doesn’t like getElementsByClassName in quirks mode or before version 9 (which you have little control over in a bookmarklet). Here’s a jsfiddle: http://jsfiddle.net/theazureshadow/vdqYG/
And if you’re curious about my experiments with importing other methods, take a look at this jsfiddle: http://jsfiddle.net/theazureshadow/ccFG3/
DISCLAIMER: Using methods from other windows in the context of the current one is dangerous, undefined territory. If you choose to use this fragile approach, make sure you test for cross-browser compatibility. My tests showed major differences in how different browsers treat this approach. You should not use this on a production site, but it might be okay for a personal bookmarklet. It is probably much safer to just include your own version of whatever method you want to use.