Paul Irish

Making the www great

How to Tweak 3rd Party Scripts "Safely"

I’m working with some code from MultiMap (basically a Google Maps clone), and unfortunately their API doesn’t support real internationalization. There are a number of strings hardcoded in English in their remotely-hosted JS, so this is my deliciously evil way of rectifying the situation.

I first started out redefining their functions in entirety, but that becomes “dangerous” when they modify a bit of code for a bug fix or something. This revised approach slips in like an evil drunken ninja and only replaces the offending parts. It’s still completely crazy, but sometimes there are no better options…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// WARNING!!  This is such a massive hack. Oh-so-hackalicious

// Problem:     Multimap doesnt allow internationalization of its buttons, etc.
// Solution:    Redefine their JS functions to use variables that are internationalized.
// Assumption:  That these internal function names stay the same. 
// Risk:        If function names change, this code will (probably) silently fail.

// The following statements change the right-click context menu items and the map/aerial/hybrid buttons.
// Instead of hard-coded strings, it will use a variable which we control.

// ON TO THE HACKS!!
// Hack 1: modify the mmjr() and mmfl() functions with funcName.toString().replace()
// Hack 2: use eval() to set the definition
// Hack 3: browser sniff because IE and FF handle toString()'d strings differently (single-quote vs double-quote)

var isIE = $.browser.msie; // jQuery browser sniff.

eval(
  "mmki.prototype.mmjr = " +
  mmki.prototype.mmjr
  .toString()
    .replace( isIE ? "'Move map to here'" : '"Move map to here"' ,      'i18n.retailLocator.moveMapToHere')
    .replace( isIE ? "'Zoom in to here'" : '"Zoom in to here"' ,        'i18n.retailLocator.zoomInToHere')
    .replace( isIE ? "'Zoom out from here'" : '"Zoom out from here"',   'i18n.retailLocator.zoomOutFromHere')
  );

eval(
  "MultimapViewer.prototype.mmfl = " +
  MultimapViewer.prototype.mmfl
  .toString()
    .replace( isIE ? "'Map'" : '"Map"',       'i18n.retailLocator.map')
    .replace( isIE ? "'Hybrid'" : '"Hybrid"', "i18n.retailLocator.hybrid")
    .replace( isIE ? "'Aerial'" : '"Aerial"', 'i18n.retailLocator.aerial')
);

Comments