Skip to content

Instantly share code, notes, and snippets.

@huang-x-h
Last active August 29, 2015 14:07
Show Gist options
  • Save huang-x-h/f146e145eaa8327e71e3 to your computer and use it in GitHub Desktop.
Save huang-x-h/f146e145eaa8327e71e3 to your computer and use it in GitHub Desktop.
globalEval
// 摘自http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
function globalEval(data) {
data = data.replace(/^\s*|\s*$/g, "");
if (data) {
var head = document.getElementsByTagName("head")[0] ||
document.documentElement,
script = document.createElement("script");
script.type = "text/javascript";
script.text = data;
head.appendChild(script);
head.removeChild(script);
}
}
window.onload = function() {
(function() {
globalEval("var test = 5;");
})();
assert(test === 5, "The code was evaluated globally.");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment