Skip to content

Instantly share code, notes, and snippets.

@nyov
Created July 19, 2013 15:31
Show Gist options
  • Save nyov/6040042 to your computer and use it in GitHub Desktop.
Save nyov/6040042 to your computer and use it in GitHub Desktop.
python spidermonkey javascript evaluation example
import os
import subprocess
def spidermonk(script, user):
""" JavaScript wrapper
smjs notes: not recommended for production use,
as it contains dangerous (security-wise) debugging features.
-- Make sure not to load unsafe javascripts!
"""
spidermonkey = '/usr/bin/smjs' # apt-get install spidermonkey-bin
jsheader = '''
// "emulate" a DOM,
// set up scripts environment
function empty(){};
window=[];
document=[];
document.write=empty;
//document.write=print;
// some custom functions
function dec2a(dec) {
function convert(all,match) {
return String.fromCharCode(parseInt(match, 10))
}
return dec.replace(/&#(\d+);/g, convert)
};
author=window.author="''' + user + '''";
'''
jsfooter = '''
// return evaluated data
print(dec2a(mstring)+a[author].substring(i))
'''
# smjs
convert = [spidermonkey,
'-e', '%s' % jsheader,
'-e', '%s' % script,
'-e', '%s' % jsfooter
]
os.environ['PYTHONIOENCODING'] = 'utf-8'
p = subprocess.Popen(
convert,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return p.communicate()[0].strip().decode('utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment