user
user

Reputation: 7333

External javascript hijacks console.log

I noticed a strange behavior whereby my console.log statements weren't doing anything. I finally tracked this to an external script:

<!-- Load the systems bio heatmap package -->
  <script type="text/javascript" src="http://systemsbiology-visualizations.googlecode.com/svn/trunk/src/main/js/load.js"></script>
  <script type="text/javascript">
//  uncommenting the following line ruins console.log
//    systemsbiology.load("visualization", "1.0", {packages:["bioheatmap"]});
  </script>

Unfortunately this script is used to run the only heatmap package for google charts (AFAIK).

Is there a way to somehow backup console.log and then restore it after executing their code? I tried doing a shallow backup but had no luck:

<!-- Load the systems bio heatmap package -->
  <script type="text/javascript" src="http://systemsbiology-visualizations.googlecode.com/svn/trunk/src/main/js/load.js"></script>
  <script type="text/javascript">
var temp = console.log;
//  the following line ruins console.log
systemsbiology.load("visualization", "1.0", {packages:["bioheatmap"]});

console.log = temp;
console.log('test'); // does not work

  </script>

Now I'm asking someone who knows what he's doing.

Thanks in advance for your help.

Upvotes: 1

Views: 1329

Answers (2)

dandavis
dandavis

Reputation: 16726

<!-- backup console log method -->
  <script> var temp = console.log.bind(console); </script>

<!-- Load the systems bio heatmap package -->
  <script src="http://systemsbiology-visualizations.googlecode.com/svn/trunk/src/main/js/load.js"></script>

<!-- restore  console log method -->
  <script>
     console.log = temp;
     console.log('test'); // does work
  </script>

EDIT: you can likely fix the code in the OP using bind:

  var temp = console.log.bind(console);

since the log() method is hard-coded to use "this" internally, we need to take "this" with us when we memorize the method.

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187252

Your code does work but only if the console object is preserved, and the methods on it are replaced.

var temp = console.log;

//  the following line ruins console.log
console.log = function() {};

// put console.log back
console.log = temp;
console.log('test');

http://jsfiddle.net/CBv2T/

If instead the console object is replaced, as I suspect is the case, this won't work. So why not save/restore the whole console object?

var temp = console;

//  the following line ruins console.log
window.console = {};

// Put the whole console object back
window.console = temp;
console.log('test');

http://jsfiddle.net/CBv2T/1/


But as @gpojd notes, this is a major bug in the library you are using. They should really fix that...

Upvotes: 4

Related Questions