I'm getting familiar with PhantomJS. But I can't get one thing. I have a page with a simple form:
<FORM action="save.php" enctype="multipart/form-data" method="GET" onSubmit="return doSubmit();">
<INPUT name="test_data" type="text">
<INPUT name="Submit" type="submit" value="Submit">
</FORM>
and a save.php just writes down the test_data value
so I'm doing this:
page.evaluate(function() {
document.forms[0].test_data.value="555";
doSubmit();
});
When rendering the page I see that text field is 555, but form isn't submitting and save.php didn't write down a test_data value. So doSubmit()
is not executing, is it? doSubmit()
is a simple validation step and a submit is supposed to load the next page.
So the question is: how can I execute a javascript code on the page, using PhantomJS?
It seems that you want to submit the form. You can achieve that in different ways, like
submit the form in the page context:
page.evaluate(function() {
document.forms[0].submit();
});
or focus on the form text field and send an enter keypress with sendEvent().
After that you will have to wait until the next page is loaded. This is best done by registering page.onLoadFinished
(which then contains your remaining script) right before submitting the form.
page.open(url, function(){
page.onLoadFinished = function(){
page.render("nextPage.png");
phantom.exit();
};
page.evaluate(function() {
document.forms[0].test_data.value="555";
document.forms[0].submit();
});
});
or you can simply wait:
page.open(url, function(){
page.evaluate(function() {
document.forms[0].test_data.value="555";
document.forms[0].submit();
});
setTimeout(function(){
page.render("nextPage.png");
phantom.exit();
}, 5000); // 5 seconds
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With