As a 3rd party developer, I often need to leverage existing site functionality without access to our client's source code. It's usually the case that we need to figure out which code is publicly accessible to reuse or extend in our A/B testing platform or tag manager.
Here's a handy function I created to inspect what unique properties are available on the window. The approach is to create a new iframe (withabout:blank
as the src) and use itscontentWindow
object as the blank canvas to compare against the parent window object to determine what properties were added to the global scope.
/** * Logs an object w/ all the unique global variables on a page * * @return {undefined} */(functioninspectUniqueGlobals(){// Create object that will contain unique global variablesconstuniqueProperties={};// Use an iframe to compare variablesconstiframe=document.createElement('iframe');// Attach blank source iframe to DOMiframe.src='about:blank';// On iframe load, process global propertiesiframe.onload=function(){// Get list of standard global objects from the iframeconstdefaultGlobals=Object.keys(iframe.contentWindow);// Loop through every window-level variablefor(letiteminwindow){constprop=window[item];/* If the property is not found in the iframe's globals, then add it to the uniqueProperties object */if(defaultGlobals.indexOf(item)===-1&&window.hasOwnProperty(item)){uniqueProperties[item]=prop;}}// Inspect unique window propertiesconsole.log(uniqueProperties);};// Add to documentdocument.body.appendChild(iframe);})();
We can test this out right on this page on dev.to if we enter this code in the console:
All of these properties are unique to the dev.to blog post page. Depending on what we're trying to achieve, we may get lucky and find a function that's already built and does exactly what we're looking for. As an example, on this page there's a globaltoggleMenu
function.
If we run it, we'll see that the user menu opens up:
window.toggleMenu();
You can learn a lot about a site with what their developers have set to the global scope. Sometimes you'll see some not-so-great things like potential vulnerabilities or even promo codes that were probably not meant to have been discovered by the average visitor. 🙊
Whatever your use case, I hope you found this handy and insightful :)
Check out more #JSBits at my blog,jsbits-yo.com. Or follow me onTwitter!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse