How to restore native browser code

How to restore native browser code

Native code is functionality that has been included by the browser's engine and not defined by you, the programmer. Some browsers like Chrome allow you to see if a function is native by simply entering it in the console (and not calling it with parentheses):

Occasionally, you may encounter a scenario where some native code has been overwritten. In my experience as a 3rd party dev, I've seen a few instances where the console has been overwritten to an empty function. This is usually done by clients who are hyper-cautious about sensitive customer information being shown (but seriously, if someone really wants to find this info they will!). Trying to write code without a functioning console is a giant pain so I had a good use case to restore the console's native functionality. (Note this was only done for local development and not deployed live!).

For example, the Khols.com mobile site has all their console methods overwritten to an empty function (Be sure to simulate the mobile site in your emulator).

So here's how we can restore it:

function createConsoleProxy() {

  // Create dummy iframe to steal its fresh console object
  const iframe = document.createElement('iframe');

  // Add iframe to current window's scope in a hidden state
  iframe.id = 'console-proxy';
  iframe.style.display = 'none';
  document.body.insertAdjacentElement('beforeend', iframe);

  // Reassign value of console to iframe's console 
  const proxyIframe = document.querySelector('#console-proxy');
  window.console = proxyIframe.contentWindow.console;
}

When we enter console.log; in the console... BAM! It's back to it's "native" state!

Before this method was used, a coworker came up with a clever alternative to view messages by creating a custom log() function that would take user input and prepend it to the body:

function log(msg) {
  const body = document.body;
  body.insertAdjacentHTML('afterbegin', `<div>${msg}</div>`);
}

This worked enough to see simple messages but we quickly realized we needed the ability to expand objects so it had limited use. But challenges like this are always fun. 🤪


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!