I want to do an HTTP POST
from inside an iMacro to an API endpoint. Effectively, something like the following:
curl -d "data=foo" http://example.com/API
In iMacros, it might look something like this:
my-imacro.iim
VERSION BUILD=10.4.28.1074
TAB T=1
URL GOTO=javascript:post('http://example.com/API', {data: 'foo'});
function post(path, params, method) {
// Reference: http://stackoverflow.com/a/133997/1640892
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
But the above seems like a long and difficult way to do this. If it even works.
Is there a shorter, more direct or efficient solution?
You can use http://wiki.imacros.net/iMacros_for_Firefox with javascript and jquery. Then it's easy with any form, get and post request thing.
Small javascript example with jquery and imacros for firefox:
function loadScriptFromURL(url) {
var request = Components.classes['@mozilla.org/xmlextras/xmlhttprequest;1'].createInstance(Components.interfaces.nsIXMLHttpRequest),
async = false;
request.open('GET', url, async);
request.send();
if (request.status !== 200) {
var message = 'an error occurred while loading script at url: ' + url + ', status: ' + request.status;
iimDisplay(message);
return false;
}
eval(request.response);
return true;
}
loadScriptFromURL('https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js');
$ = window.$,
JQuery = window.JQuery;
If you are searching for more clean and efficient solution it's need to know that JavaScript will work only in Firefox iMacros plugin. And this script will not work with iMacros plugin version 9.0.3
http://wiki.imacros.net/iMacros_for_Firefox#Version_History
No access to webpage DOM from javascript in .js files (window, content
objects) or macros (URL GOTO=javascript:...)
It's better to change API endpoint method to GET. Next you can create iMacros .iim file that extract from web page some properties and send it by GET method to the API endpoint like http://localhost/endpoint?param1=value1¶m2=value2..
' extract header
TAG POS=1 TYPE=span ATTR=id:header EXTRACT=txt
SET !VAR1 header={{!EXTRACT}}
SET !EXTRACT NULL
' extract phone
TAG POS=1 TYPE=span ATTR=class:phone EXTRACT=txt
SET !VAR1 {{!VAR1}}&phone={{!EXTRACT}}
SET !EXTRACT NULL
' ///open new tab
TAB OPEN
TAB T=2
' ///Basic Auth credentials to API Endpoint
ONLOGIN USER=XXX PASSWORD=XXX
URL GOTO=http://localhost:8080/endpoint?{{!VAR1}}