null for elements in phantomjs - javascript

I have this code running in the phantomjs. I don't know why form.elements keeps returning null to me. I ran the same code on chrome developer console and got the right result i want.
I'm pretty new to javascript and everything related. Please shed some light.
var page = require('webpage').create();
page.open('http://www.kayak.com', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var form = page.evaluate(function(){
return document.getElementById('searchform');
});
console.log(form.elements[2].value);
}
phantom.exit();
});

You can't pass a non-primitive object through evaluate. This is mentioned in the documentation:
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!
Although it is the most common mistake when using PhantomJS, this is rather easy to solve. Just make sure you do all the processing as much as you can within evaluate and then return back a simple object. For details, please study the documentation carefully and learn from all the included examples.

Related

Does a truthy value in JavaScript always have a hasOwnProperty method?

Here we can see which types of objects in JavaScript/ECMAScript evaluate to false.
My question is: if a variable evaluates to true, is it guaranteed to have a hasOwnProperty method?
In other words, is the following test safe?
if (bar && bar.hasOwnProperty("foo")) { ... }
My goal is to prevent exceptions like Cannot read property 'hasOwnProperty' of null.
My application scenario: in an AngularJS $http service error handler I want to be prepared for all situations. This is a little difficult for me, because I am not tremendously experienced with JavaScript and the different situations in which this error handler might be called can not easily be tested for. The error handler function has the following signature:
function(data, status, headers, config) {}
In the function body I evaluate data like so:
if (data && data.hasOwnProperty("error")) {
alert(data.error);
}
Does this look safe to you under all circumstances? Safe in the sense that this test does not throw an exception, no matter how AngularJS actually calls the error handler.
No.
Here's one:
var bar = Object.create(null);
Here's another one with hasOwnProperty, but not much better:
var bar = {hasOwnProperty:function(){ throw "bouh" }};
But you can call
Object.prototype.hasOwnProperty.call(bar, "foo")
Note that you may avoid the evaluation to truthy by doing
if (Object.prototype.hasOwnProperty.call(Object(bar), "foo")) {

Javascript throw vs. return error object vs. callback

I'm writing an assembler and simulator for a toy assembly language that I have my CS students use in class. I'm writing it in javascript with the idea that I could then build a simple UI in the browser which would show students how each instruction changes the state of the machine and such.
One question that I'm grappling with is the best way to return error information from the assembler when invalid assembly code is passed. The assembler has an extremely simple API at the moment:
var assembler = ... // Get the assembler object
var valid_source = "0 mov r1 r2\n1 halt";
var valid_binary = assembler.assemble(valid_source); // String containing 0's and 1's
var invalid_source = "foo bar baz!";
var invalid_binary = assembler.assemble(invalid_source); // What should happen here?
I have a few thoughts about how this might work:
Construct and throw a new javascript Error object. This seems like overkill (and ultimately maybe not even helpful since the user wouldn't care about the javascript stacktrace, etc).
Return a string or object containing error information. Then the user of the assembler gets to make the choice about what to do with errors (if anything).
Change the assembler API to use a callback instead:
assembler.assemble(source, function(binary, error) {
if (error) {
// Handle the error
}
// Otherwise, do stuff with the binary
});
Something else entirely?
Any ideas, thoughts, or feedback would be much appreciated.
I think your three options would work fine. Now from my perspective:
I would keep away from the third option because it gives the feeling it is an async function when it is not.
I would go for option 1 or 2. The first one is a little overkill but I think it is the most realistic approach to what compilers do. Exit with no zero code. But then you would need to add a try/catch block to handle the error.
So the next option is to return an error object. Seems the best option for me.
I recommend you to return an Error object. It is as simple as:
return new Error('Parsing error');
// Or with an error name
var error = new Error('Parsing error');
error.name = 'PARSING_ERROR';
return error;
One advantage to use the error object is that it gives you the stack trace and other handy stuff. More info here.
Also, to check if there was any error just need to check the variable type:
if (typeof valid_binary === 'string') { /* no error */ }
// Or
if (typeof valid_binary === 'object') { /* error */ }
Good luck!

Calling a default method in Js Object

Is there any way to create an object that respond to any message? Suppose you have the following object:
function Dog();
Dog.prototype.speak(){
alert("woof woof");
}
var myDog = new Dog();
Then when you do myDog.speak() you will get an alert with "Woof woof". But what I want is when you call myDog.jump() (which is not defined in the class) you will get a default action like show the user an alert with "you are trying to excecute an inexistent method".
Do you know how can I do it?
Short answer: you can't.
Long answer: you could use __noSuchMethod__ but it's not standard and there are some plans to remove it, because Proxy can do the same, and more. Plus, it's a standard.
Therefore, you could use a Proxy to do that, but I would discourage to have all objects as proxies, because performance reasons.
Personally, I would just leave the language thrown it's own exception, that the developer can check in the error console.
There is no standards-based way to do this. The closest thing is this.
The closest you could get to this would be:
function execute(obj, message, args) {
if (obj[message] && typeof(message) === function) {
obj[message].call(obj, args);
} else {
obj[message] = function() {
//missing method functionality a la Ruby here
};
}
}
Others have already mentioned __noSuchMethod__ and Proxy so I'll refrain from going into further detail on those.
Instead, I wanted to highlight another technique that may be able to do what you want. Please be aware that this is a ugly hack, I can't encourage it's usage and it may not even work in all of your targets. With those caveats in mind, I present you with window.onerror:
window.onerror = function(err) {
if (/has no method/.test(err)) {
console.log('oh my: ' + err) // This is where you'd call your callback
return true
}
return false
}
;(function() {
this.foo() // will be caught by window.onerror
})()
This – at least in my very limited testing – catches TypeErrors (in Chrome at least, mileage may vary) that signified that the method could not be found. Here are some of the reasons why you should not do this:
window.onerror can only have one handler; if your handler is overwritten this won't work
It catches TypeErrors globally, not just for a specific object; i.e. lot's of false positives
It'll make it fun to debug for anyone coming in not knowing where to find this handler
It tightly couples any bit of code you have that relies on this behavior (bad, bad, bad!)
I don't think I can stress enough how much you really shouldn't be thinking of hacking this in. Use Proxy if you can, admit defeat if you can't.

Calling a method within a Javascript Object

I'm trying to create a javascript object that can call other methods within itself. However, I'm running into a weird problem that I just can't seem to figure out.
I have the following code
myObjectDef = function() {
this.init = function() {
//do some stuff
this.doSecondInit();
}
this.doSecondInit = function() {
//do some more stuff
}
}
myObject = new myObjectDef();
myObject.init();
I am getting an error that states "Message: Object doesn't support this property or method". And it ends at this.doSecondInit();. I can't quite figure out why it's doing this. My code runs great up to the call to the second method. How do I make this work?
There's an extra set of parenthesis here:
this.doSecondInit() = function() {
You can't assign to the result of a function call, let alone to the result of a function that doesn't even exist.
After your edit, your thing seems to work fine:
http://jsfiddle.net/nabVN/
You sure you didn't have the same typo in your actual code? Better start getting used to not putting that () after every function call, which is probably a bad habit carried over from languages where functions aren't values.

call function using if statement

I want to be able to call a function within an if statement.
For example:
var photo = "yes";
if (photo=="yes") {
capturePhoto();
}
else {
//do nothing
};
This does nothing though. The function is clearly defined above this if statement.
Edit: Wow, downboated to hell! capturePhoto(); was just an example function that didn't really need any more explanation in this scenario?
That should work. Maybe capturePhoto() has a bug?
Insert an alert() or console.log():
var photo = "yes";
if (photo == "yes") {
alert("Thank you StackOverflow, you're a very big gift for all programmers!");
capturePhoto();
} else {
alert("StackOverflow.com must help me!");
}
I'm not seeing any problems here. I used this code and the function call worked. I kept your code and just added a function called capturePhoto().
Are you sure that the code you're using to call the function is firing?
var photo = "yes";
if (photo=="yes")
{
capturePhoto();
}
else
{
//do nothing
};
function capturePhoto()
{
alert("Pop up Message");
}
You probably missed something, a quotation, a semicolon or something like that. I would recommend you to use a debugger like Firebug or even Google Chrome's Web Developer Tool. You will know what's wrong with your code and where it is wrong.
You may take a look at this live code that your code above works: http://jsfiddle.net/ZHbqK/
The code looks fine to me (except you don't need the ; at the end of the last line). Check your error log; perhaps the browser thinks capturePhoto is not defined for some reason. You can also add alert statements to make sure the code is actually running:
var photo = "yes";
alert('Entering if statement');
if (photo=="yes") {
alert('then');
capturePhoto();
} else {
alert('else');
//do nothing
}
When you encounter a situation where it seems like a fundamental language feature is not working, get some more information about what is going on. It is almost never the platform's fault. It is occasionally a misunderstanding of how the feature works (e.g. why does parseInt('031') == 25 ?). It is usually a violation of an assumption you're making about the code that isn't holding up because of a problem elsewhere.
You should also consider using true and false instead of strings that could be manipulated depending on input.
If I had to correct the following code, then I should've done it like this;
var photo = true; // Will capture picture.
if (photo) { // 'true' is a truthy value.
capturePhoto();
} else {
// Do nothing
}
The code that you posted does work.
I copied it and tested it.
Demo: http://jsfiddle.net/Guffa/vraPQ/
The only thing wrong with it that I can see is a semicolon after the closing bracket, but that is only a style problem. It will form an extra empty statement, but that doesn't cause any problems.

Categories