Reputation: 83
Is there a solution to get the "foo bar" in JS (with jQuery ?) in this code ?
<!DOCTYPE html>
<html>
<body role="application" onload="foo bar">
<div>...</div>
</body>
</html>
I'am using PhantomJS in my script.
EDIT: "foo bar" is an example. It's juste the value I would get.
EDIT 2: my code (wich don't work) is http://paste.awesom.eu/nca&ln.
EDIT 3: PROBLEM(S) AND SOLUTION
After many hours I find many problems and solutions.
First, the website is only accesible in https and I can't include jQuery file from non https url. That's why I have include the jQuery file from the website.
I have debug this with this code :
page.onConsoleMessage = function(msg) {
console.log(msg);
};
Then, I need to change my user agent because the website has a whitelist.
page.settings.userAgent = 'Mozilla/5.0 (X11; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/25.0';
Finaly the code is:
page.open(url, function(status) {
if ( status === "success" ) {
page.includeJs(url_js_file, function() {
page.evaluate(function() {
console.log("> " + $("body").attr("onload"));
});
phantom.exit();
});
}
});
Thank you for comments and anwers.
Upvotes: 0
Views: 1383
Reputation: 141
It looks like you are not returning your variable out of evaluate. To do that you must
var bodyonload = page.evaluate(function (s) {
return document.body.getAttribute('onload');
}, 'bodyonload');
You were very close to having it.
Here is your code where it returns an object rather than just a variable. I figured it could be useful.
page.open(url, function (status) {
if (status !== 'success') {
console.log('FAILED: ' + status);
} else {
var result = page.evaluate(function (s) {
var result = {
bodyOnLoad: document.body.getAttribute('onload'),
documentTitle: document.title
};
return result;
}, 'result');
console.log(result.bodyOnLoad);
}
phantom.exit();
});
Hope that helps
page.injectJs()
, is jquery in the same directory?
Upvotes: 1
Reputation: 1969
This worked for me for returning the value in onload
.
<!DOCTYPE html>
<html>
<body role="application" onload="foo bar">
<div>...</div>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
console.log($("body").attr("onload"));
</script>
</body>
</html>
Upvotes: 0
Reputation: 1548
If you want to get the actual, literal value of onload
, use $('body').attr('onload')
. This will return the value of any attribute, for any element (assuming jQuery is being used). If not using jQuery, document.body.getAttribute("onload")
should do the trick.
Keep in mind that since PhantomJS technically runs outside of the targeted page's DOM, you need to wrap any DOM scripts in page.evaluate
:
page.evaluate(function () {
// put your $('body').attr('onload') bit here.
});
Upvotes: 0
Reputation: 22711
There should be no space between function name, It should like <body role="application" onload="foobar()">
instead of <body role="application" onload="foo bar">
In between HTML head tag,
<script>
function foobar(){
alert('Am loaded');
}
</script>
Upvotes: 0