instance method String#evalScripts

View source on GitHub →

String#evalScripts() → Array

Evaluates the content of any inline <script> block present in the string. Returns an array containing the value returned by each script. <script> blocks referencing external files will be treated as though they were empty (the result for that position in the array will be undefined); external files are not loaded and processed by String#evalScripts.

Examples
'lorem... <script>2 + 2</script>'.evalScripts();
// -> [4]
 '<script>2 + 2<script><script>alert("hello world!")</script>'.evalScripts();
// -> [4, undefined] (and displays 'hello world!' in the alert dialog)
About evalScripts, vars, and defining functions

String#evalScripts evaluates script blocks, but this does not mean they are evaluated in the global scope. They aren't, they're evaluated in the scope of the String#evalScripts method. This has important ramifications for your scripts:

  • Anything in your script declared with the var keyword will be discarded momentarily after evaluation, and will be invisible to any other scope.
  • If any <script> blocks define functions, they will need to be assigned to properties of the window object.

For example, this won't work:

// This kind of script won't work if processed by evalScripts:
function coolFunc() {
  // Amazing stuff!
}

Instead, use the following syntax:

// This kind of script WILL work if processed by evalScripts:
window.coolFunc = function() {
  // Amazing stuff!
}

(You can leave off the window. part of that, but it's bad form.)