The renewal maintenance has officially ended for Progress iMacros effective November 30, 2023.
This Wiki site will also no longer be moderated from the Progress side.
Thank you again for your business and support.
Sincerely, The Progress Team
Difference between revisions of "EVAL"
(35 intermediate revisions by 4 users not shown) | |||
Line 1: | Line 1: | ||
− | This command allows you to '''eval'''uate values, and trigger macro errors if certain conditions are met. It can can also be used to convert and modify extracted content. | + | This command allows you to '''eval'''uate 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: | Example uses: | ||
− | * Detect if e. g. date is "older than 40 days" | + | * Detect if e.g. date is "older than 40 days" |
− | * Detect if a number, e. g. exchange rate is above/below a certain value | + | * 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 | + | * 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 [[Image:IMacros-icon.png|iMacros Browser]] [[Image:Ie-icon.png|IE Plug-in]] [[Image:Ff-icon.png|Firefox]]=== | + | ===Syntax [[Image:IMacros-icon.png|iMacros Browser]] [[Image:Ie-icon.png|IE Plug-in]] [[Image:Ff-icon.png|Firefox]] [[Image:Cr-icon.png|Chrome]]=== |
SET !VAR1 EVAL("[javascript statements]") | 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=== | ===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 [[Error_and_Return_Codes#Macro_Playback|iMacros error -1340]], where the error text is the string argument <tt>errorMsg</tt>. | ||
+ | |||
+ | Use this function if you want to conditionally stop the macro, as it is done in [[EVAL#Parse_and_compare_currency._Conditionally_save|Example 2]] below. | ||
+ | |||
+ | ===Notes=== | ||
+ | |||
+ | # 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 | ||
+ | # 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. | ||
+ | # You can call the special function MacroError(errorMsg) in the Javascript to generate an iMacros error. | ||
+ | # You must escape backslash characters with a backslash, e.g. \d becomes \\d in your code. | ||
+ | # Double-quote characters must also be escaped since the entire Javascript expression to be evaluated must be surrounded in double-quotes. | ||
+ | # EVAL in iMacros Browser and the IE plugin use [http://msdn.microsoft.com/en-us/library/xkx7dfw1(v=VS.90).aspx Microsoft's JScript 8.0] (JScript .NET, framework version 3.5) [http://msdn.microsoft.com/en-us/library/b51a45x6(v=VS.90).aspx 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#Using_Javascript|URL GOTO with Javascript]]. | ||
+ | # iMacros for Firefox's EVAL uses Firefox javascript engine. | ||
===Examples === | ===Examples === | ||
+ | |||
+ | ====Random wait==== | ||
+ | |||
Wait for a random time (1 to 10 seconds) after a page is loaded: | 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;") | |
− | SET !VAR1 EVAL("var | ||
URL GOTO=http://www.iopus.com | URL GOTO=http://www.iopus.com | ||
' waits 1 to 10 seconds | ' waits 1 to 10 seconds | ||
WAIT SECONDS=<nowiki>{{!VAR1}}</nowiki> | WAIT SECONDS=<nowiki>{{!VAR1}}</nowiki> | ||
− | + | ====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 [http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range 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 | URL GOTO=http://www.xe.com/ucc/convert/?Amount=1&From=EUR&To=USD | ||
SET !EXTRACT_TEST_POPUP NO | SET !EXTRACT_TEST_POPUP NO | ||
Line 35: | Line 66: | ||
SET !EXTRACT NULL | SET !EXTRACT NULL | ||
SET !EXTRACT <nowiki>{{!VAR1}}</nowiki> | SET !EXTRACT <nowiki>{{!VAR1}}</nowiki> | ||
− | SAVEAS TYPE=EXTRACT FOLDER=* FILE=EuroRate.csv | + | 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=\"<nowiki>{{!EXTRACT}}</nowiki>\"; 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 <nowiki>{{tomorrow}}</nowiki> | ||
+ | |||
+ | ====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 <nowiki>s=\"{{!EXTRACT}}\"</nowiki>; s.toUpperCase()") | ||
+ | PROMPT <nowiki>{{!VAR1}}</nowiki> | ||
+ | |||
+ | 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 <nowiki>|{{!EXTRACT}}|</nowiki> | ||
+ | SET trimmedValue <nowiki>EVAL("\"{{!EXTRACT}}\".replace(/^\\s*|\\s*$/g, \"\");")</nowiki> | ||
+ | PROMPT <nowiki>"|{{trimmedValue}}| - not anymore!"</nowiki> | ||
+ | |||
+ | ====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=<nowiki>{{!VAR1}}</nowiki> | ||
+ | SET !EXTRACT_TEST_POPUP NO | ||
+ | TAG POS=1 TYPE=B ATTR=TXT:* EXTRACT=TXT | ||
+ | SET !VAR2 EVAL("var h=20; var s=\"<nowiki>{{!EXTRACT}}</nowiki>\"; 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=\"<nowiki>{{!EXTRACT}}</nowiki>\"; var d = parseFloat(s); if((d>99)&&(d<101))d; else MacroError(\"Value is not in the set range\");") | ||
+ | |||
+ | ===Related Forum Posts=== | ||
+ | |||
+ | * [http://forum.iopus.com/viewtopic.php?f=11&t=19759 BUG or SYNTAX Error? EVAL in Macro in Javascript] | ||
===See Also === | ===See Also === | ||
− | [[TAG]], [[SET]] | + | [[TAG]], [[SET]], [[URL#Using_Javascript|URL GOTO with Javascript]] |
Revision as of 10:06, 25 March 2015
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
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
- 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
- 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.
- You can call the special function MacroError(errorMsg) in the Javascript to generate an iMacros error.
- You must escape backslash characters with a backslash, e.g. \d becomes \\d in your code.
- Double-quote characters must also be escaped since the entire Javascript expression to be evaluated must be surrounded in double-quotes.
- 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.
- 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\");")