EVAL

From iMacros
Revision as of 13:06, 25 March 2015 by Td (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This command allows you to evaluate values, and trigger macro errors if certain conditions are met. It can can also be used to convert and modify extracted content. Inside EVAL, you have the full power of Javascript's eval statement available!

Example uses:

  • Detect if e.g. date is "older than 40 days"
  • Detect if a number, e.g. exchange rate is above/below a certain value
  • Make small clean-up operations. If the extracted text is "US$33.33" you might remove the "US$" part before saving it via SAVEAS TYPE=EXTRACT


Syntax iMacros Browser IE Plug-in Firefox Chrome

SET !VAR1 EVAL("[javascript statements]")
TAG ... CONTENT=EVAL("[javascript statements]")

Available in iMacros V7.5 and later, iMacros for Firefox 7.4.0.1 and later

Parameters

A string value surrounded by double-quotes containing the Javascript code to execute.

Function MacroError(errorMsg)

Besides the standard javascript functions (in IE and the iMacros Browser, JScript 8.0), iMacros' EVAL has a predefined error output function: MacroError().

MacroError accepts a string as argument and, if evaluated, throws an iMacros error -1340, where the error text is the string argument errorMsg.

Use this function if you want to conditionally stop the macro, as it is done in Example 2 below.

Notes

  1. You need to explicitly return the final value by adding it as a single statement to the end of the Javascript.
    Correct: SET myVal EVAL("var x = 1; x;") // myVal = 1
    Incorrect: SET myVal EVAL("var x = 1;") // myVal = null
  2. The code evaluation occurs in an execution context that is separate from the browser process, therefore access to the web page DOM is not available.
  3. You can call the special function MacroError(errorMsg) in the Javascript to generate an iMacros error.
  4. You must escape backslash characters with a backslash, e.g. \d becomes \\d in your code.
  5. Double-quote characters must also be escaped since the entire Javascript expression to be evaluated must be surrounded in double-quotes.
  6. EVAL in iMacros Browser and the IE plugin use Microsoft's JScript 8.0 (JScript .NET, framework version 3.5) eval method, so security restrictions apply.
    As a consequence, DOM/GUI methods like "compatMode()" or "alert()" are not available. (this also applies to iMacros for Firefox)
    For DOM/GUI access you can use URL GOTO with Javascript.
  7. iMacros for Firefox's EVAL uses Firefox javascript engine.

Examples

Random wait

Wait for a random time (1 to 10 seconds) after a page is loaded:

SET !VAR1 EVAL("var randomNumber=Math.floor(Math.random()*10 + 1); randomNumber;")
URL GOTO=http://www.iopus.com
' waits 1 to 10 seconds
WAIT SECONDS={{!VAR1}}

Generate a random number within a specific range

SET randomNumber EVAL("var min = 50; var max = 100; var randomNumber = Math.floor(Math.random() * (max - min + 1)) + min; randomNumber;")

See also Generating random numbers in Javascript in a specific range.

Parse and compare currency. Conditionally save

Save EUR rates in USD only if it is above a certain threshold (1.3 USD). If it is below, stop the macro and give an error:

URL GOTO=http://www.xe.com/ucc/convert/?Amount=1&From=EUR&To=USD
SET !EXTRACT_TEST_POPUP NO
TAG POS=1 TYPE=TD ATTR=TXT:*<SP>USD&&WIDTH:46%&&ALIGN:left EXTRACT=TXT
SET !VAR1 EVAL("var s=\"{{!EXTRACT}}\"; s.replace(\"USD\",\"\"); var d=parseFloat(s); if(d < 1.3){MacroError(\"Euro is below 1.3 USD.\");} else d;")
SET !EXTRACT NULL
SET !EXTRACT {{!VAR1}}
SAVEAS TYPE=EXTRACT FOLDER=* FILE=EuroRate.csv

Parse and compare date/time

Check if the most recent post is older than some hours (12 hours):

CLEAR
URL GOTO=http://www.readwriteweb.com/
SET !EXTRACT_TEST_POPUP NO
TAG POS=1 TYPE=DIV ATTR=CLASS:submeta EXTRACT=TXT
SET !VAR1 EVAL("var h=12; var s=\"{{!EXTRACT}}\"; var re=/\\w+\\s\\d{1,2},\\s\\d{4}\\s+\\d{1,2}\\:\\d{2}\\s[A|P]M/; var postDateStr=re.exec(s); var today=new Date(); var postAge=today.getTime()-Date.parse(postDateStr); var hInMilli=h*60*60*1000; if(postAge>hInMilli){MacroError(\"Post is older than 12 hours\");}")

Get yesterday's date

Fill in a text input with yesterday's date in ISO format (yyyy-mm-dd), aware of month changes, leap year, etc. For today's date we can use !NOW, but it is not possible to obtain a date relative to today this way. EVAL solves this problem.

... CONTENT=EVAL("var d=new Date();d.setDate(d.getDate()-1);var year=d.getFullYear();var month=d.getMonth()+1;var day=d.getDate();year+'-'+month+'-'+day;")

Get tomorrow's date

Create a variable with tomrrow's date in dd/mm/yyyy format.

SET tomorrow EVAL("var today = new Date(); var tomorrow = new Date(); tomorrow.setDate(today.getDate() + 1); var day = tomorrow.getDate().toString(); if (day.length < 2) {day = \"0\" + day;} var month = (tomorrow.getMonth() + 1).toString(); if (month.length < 2) {month = \"0\" + month;} var year = tomorrow.getFullYear().toString(); var dateString = day + \"/\" + month + \"/\" + year; dateString;")
PROMPT {{tomorrow}}

Manipulate extraction

Transform extraction to uppercase characters:

VERSION BUILD=7400919 RECORDER=FX
TAB T=1
URL GOTO=http://android-developers.blogspot.com/2011/09/preparing-for-handsets.html
SET !EXTRACT_TEST_POPUP NO
TAG POS=1 TYPE=P ATTR=TXT:Early<SP>this<SP>year,* EXTRACT=TXT
SET !VAR1 EVAL("var s=\"{{!EXTRACT}}\"; s.toUpperCase()")
PROMPT {{!VAR1}}

Trim leading and trailing spaces:

SET !EXTRACT "    This value has leading and trailing spaces     "
' Display the value within vertical bars to emphasize the spaces
PROMPT |{{!EXTRACT}}|
SET trimmedValue EVAL("\"{{!EXTRACT}}\".replace(/^\\s*|\\s*$/g, \"\");")
PROMPT "|{{trimmedValue}}| - not anymore!"

Demo Eval.iim

Demo Eval.iim:

URL GOTO=http://www.iopus.com/imacros/demo/v7/eval.htm
SET !VAR1 EVAL("Math.floor(Math.random()*5 + 1);")
WAIT SECONDS={{!VAR1}}
SET !EXTRACT_TEST_POPUP NO
TAG POS=1 TYPE=B ATTR=TXT:* EXTRACT=TXT
SET !VAR2 EVAL("var h=20; var s=\"{{!EXTRACT}}\"; var today=new Date(); var postAge=today.getTime()-Date.parse(s); var hInMilli=h*60*60*1000; if(postAge>hInMilli){MacroError(\"Time deviates more than 20 hours\");}else null")
SET !EXTRACT NULL
TAG POS=1 TYPE=INPUT:TEXT FORM=ID:form1 ATTR=NAME:textfield EXTRACT=TXT
SET !VAR2 EVAL("var s=\"{{!EXTRACT}}\"; var d = parseFloat(s); if((d>99)&&(d<101))d; else MacroError(\"Value is not in the set range\");")

Related Forum Posts

See Also

TAG, SET, URL GOTO with Javascript