How to understand "document" of page evaluation code in phantomjs? - phantomjs

How to understand "document" in below code?
*var page = require('webpage').create();
page.open(url, function(status) {
var title = page.evaluate(function() {
return document.title;
});*
The function in evaluation part does not define what is the document so I feel very confused where this document comes from.

Related

casperJS Can't find variable : $

I'm trying to call a function defined in another module using this.evaluate().
The code snippet(calling the function) is:
this.waitFor(function check() {
var re = this.evaluate(universe.answer(couponElement, url));
if (re != 'no' & re!='yes' & re!=null) {
couponObj.push(re);
and the module in which the function is defined is like this:
var require = patchRequire(require);
var utils = require('utils');
exports.answer = function(couponElement, url) {
var lblInvalidCoupon = 'lblInvalidCoupon';
var tolTipCouponinner='tolTipCouponinner';
var txtFCCoupondisocunt = 'txtFCCoupondisocunt';
var btnRemoveFCCoupon = 'btnRemoveFCCoupon';
var check = $('#txtCouponCode').css('backgroundImage');
if (check.indexOf('ajax-loader.gif')>-1){
return 'no';
} else {
if (document.getElementById(lblInvalidCoupon)!=null){
Basically, I want to call the function using this.evaluate but unable to do so.
First, try with the simplest evaluate: remote.message event to capture console.log from page.
casper.on("remote.message", function(msg) {
console.log("[page] " + msg);
});
this.evaluate(function () {
console.log("Hi phantomworld! I am hello-ing from remote page!");
});
Next, check if jQuery is present:
this.evaluate(function () {
console.log(typeof jQuery);
});
If it says, [page] function, jQuery is present in the page. You need to dig more...
If not, inject it:
var casper = require('casper').create({
clientScripts: [
'includes/jquery.js'
]
});
You didn't actually pass the answer function to casper.evaluate, but you called it instead. The problem is that in this way answer was not executed in page context and because of this $ is not defined. casper.evaluate which executes a function in page context is sandboxed. It cannot use variables which are defined outside. The passed function must be self contained.
To fix this the arguments which are consumed by answer can be passed as additional parameters to casper.evaluate.
Change the line
var re = this.evaluate(universe.answer(couponElement, url));
to
var re = this.evaluate(universe.answer, couponElement, url);
If JQuery is not present in the page you need to follow sudipto's answer.

Problems with var page = $(this).attr("id");

i have been working for hours on the live search concept, and i am having problems with just one part of the Code.
html
<input id="searchs" autocomplete="off" />
<div class="livesearch" ></div>
javascript
$(function () {
$("#searchs").keyup(function () {
var searchs = $(this).val();
$.get("livesearch.php?searchs=" + searchs, function (data) {
if (searchs) {
$(".livesearch").html(data);
} else {
$(".livesearch").html("");
}
});
});
$(".page").live("click", function () {
var searchs = $("#searchs").val();
var page = $(this).attr("id");
$(".livesearch").load("livesearch.php?searchs=" + searchs + "&page=" +page);
});
});
the part var page = $(this).attr("id"); is not working. The page shows the error below
Notice: Undefined index: page in C:\xamp\...
and this error comes from the livesearch.php file which intends to use the index.
I am new to this way of scripting.
what could be the problem?
the part where the error is coming from on livesearch.php
if($_GET["page"]){
$pagenum = $_GET["page"];
} else {
$pagenum = 1;
}
Try this:
$(".livesearch").load("livesearch.php", {
searchs: searchs,
page: page
});
You weren't properly encoding the search string, and it could cause problems parsing the URL. jQuery will do that for you if you put the parameters in an object.

Retrieve all forms on Webpage

How can I retrieve all the forms that are present on the given website. Specifically the id and name of a form.
Thanks
Simply with something like that
var page = require('webpage').create();
page.open('yoursitehere', function (status) {
if (status !== 'success') {
console.log('unable to access network');
} else {
var forms = page.evaluate(function(){
//best way here
return document.forms;
});
//some stuff here
console.log(forms.length);
console.log(forms[0].name);
}
phantom.exit();
});
also, note that can't pass a non-primitive object through evaluate. You will have to do your work in the evaluate.
Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine. Closures, functions, DOM nodes, etc. will not work!

making safari extension in context menu. When over image mouse right click, how i know image url?

Making safari extension imageSearch By google.
Here is my source.
injected.js
document.addEventListener("contextmenu", handleContextMenu, false);
function handleContextMenu(event) {
safari.self.tab.setContextMenuEventUserInfo(event, event.target.nodeName);
}
global.html
<!DOCTYPE HTML>
<script type="text/javascript" src="jquery.js"></script>
<script>
safari.application.addEventListener("contextmenu", handleContextMenu, false);
function handleContextMenu(event) {
var query = event.userInfo;
if (query === "IMG") {
event.contextMenu.appendContextMenuItem("imageSearch", "Search Google with this image");
}
}
safari.application.addEventListener("command", performCommand, false);
function performCommand(event) {
if (event.command === "imageSearch") {
/*How I get image Url??? */
var imageUrl="";
/*
var url = "http://images.google.com/searchbyimage?image_url="+imageUrl;
var tab = safari.application.activeBrowserWindow.openTab("foreground");
tab.url = url;
*/
}
}
My goal is..
if mouse rightclick add "Search by Google With This Image" int the context menu. (clear)
and click "Search by Google With This Image" google it. (???)
so i want to know image url.
What should I do?
You could try this:
store the whole node into the event's userInfo:
function handleContextMenu(event) {
safari.self.tab.setContextMenuEventUserInfo(event, event.target);
}
add some global javascript variable to your global.html (e.g. var lastClickedImg),
change your handleContextMenu function to store the event.userInfo in function handleContextMenu to this variable:
function handleContextMenu(event) {
var query = event.userInfo;
if (query.nodeName === "IMG") {
lastClickedImg = query;
event.contextMenu.appendContextMenuItem("imageSearch", "Search Google with this image");
}
}
in your function performCommand you will easily get the image's url from lastClickedImg:
lastClickedImg.src
You can find image URL by placing an event listener for contextmenu in an injected script.
function contextMenuHandler(event)
{
var url = event.target.src;
safari.self.tab.setContextMenuEventUserInfo(event, url);
}
document.body.addEventListener("contextmenu", contextMenuHandler, false);
And then recovering the image src in command event
var imageUrl = event.userInfo;
You should also do some validation to make sure it's an image.

Can I use Ext's loader to load non-ext scripts/object dynamically?

In my ExtJS 4.0.7 app I have some 3rd party javascripts that I need to dynamically load to render certain panel contents (some fancy charting/visualization widgets).
I run in to the age-old problem that the script doesn't finish loading before I try to use it. I thought ExtJS might have an elegant solution for this (much like the class loader: Ext.Loader).
I've looked at both Ext.Loader and Ext.ComponentLoader, but neither seem to provide what I'm looking for. Do I have to just "roll my own" and setup a timer to wait for a marker variable to exist?
Here's an example of how it's done in ExtJS 4.1.x:
Ext.Loader.loadScript({
url: '...', // URL of script
scope: this, // scope of callbacks
onLoad: function() { // callback fn when script is loaded
// ...
},
onError: function() { // callback fn if load fails
// ...
}
});
I've looked at both Ext.Loader and Ext.ComponentLoader, but neither
seem to provide what I'm looking for
Really looks like it's true. The only thing that can help you here, I think, is Loader's injectScriptElement method (which, however, is private):
var onError = function() {
// run this code on error
};
var onLoad = function() {
// run this code when script is loaded
};
Ext.Loader.injectScriptElement('/path/to/file.js', onLoad, onError);
Seems like this method would do what you want (here is example). But the only problem is that , ... you know, the method is marked as private.
This is exactly what newest Ext.Loader.loadScript from Ext.4-1 can be used for.
See http://docs.sencha.com/ext-js/4-1/#!/api/Ext.Loader-method-loadScript
For all you googlers out there, I ended up rolling my own by borrowing some Ext code:
var injectScriptElement = function(id, url, onLoad, onError, scope) {
var script = document.createElement('script'),
documentHead = typeof document !== 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
cleanupScriptElement = function(script) {
script.id = id;
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
return this;
},
onLoadFn = function() {
cleanupScriptElement(script);
onLoad.call(scope);
},
onErrorFn = function() {
cleanupScriptElement(script);
onError.call(scope);
};
// if the script is already loaded, don't load it again
if (document.getElementById(id) !== null) {
onLoadFn();
return;
}
script.type = 'text/javascript';
script.src = url;
script.onload = onLoadFn;
script.onerror = onErrorFn;
script.onreadystatechange = function() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
onLoadFn();
}
};
documentHead.appendChild(script);
return script;
}
var error = function() {
console.log('error occurred');
}
var init = function() {
console.log('should not get run till the script is fully loaded');
}
injectScriptElement('myScriptElem', 'http://www.example.com/script.js', init, error, this);
From looking at the source it seems to me that you could do it in a bit of a hackish way. Try using Ext.Loader.setPath() to map a bogus namespace to your third party javascript files, and then use Ext.Loader.require() to try to load them. It doesn't look like ExtJS actually checks if required class is defined in the file included.