In a plug-in I am using NPN_Evaluate() to execute some Javascript. How can I detect wether the Javascript raises an exception? Basically I want to execute any piece of Javascript and get the result from it or detect if it raised an exception.
I tried wrapping my Javascript code like this:
try {
// Injected Javascript code here
}
catch (exc) {
exc;
}
That way the result from NPN_Evaluate() will be an NPObject* containing a property "message" with the exception message if something goes wrong. But how can I know that it is an exception? It 开发者_Go百科might as well be a result from the injected Javascript code.
Am I approaching this the wrong way? Can I detect an exception without catching it in Javascript and returning the exception as the result?
Personally I've never been a fan of using NPN_Evaluate; If I needed to do something that couldn't be done using other methods (NPN_Invoke, NPN_GetProperty, etc) I'd use NPN_Evaluate to inject a javascript function into the DOM and then call it using NPN_Invoke; then if it returns false you know it failed. There isn't any really good exception handling across that bridge, unfortunately, but the return value of true or false will tell you if it succeeded -- I suspect this holds true even for just using NPN_Evaluate.
Remember that anything declared global in javascript is a property of the window; thus, if you inject "function foo(bar) { alert(bar); }" with NPN_Evaluate you can use NPN_GetValue to get the Window NPObject and then call GetProperty("foo") to get the foo function. You can then call InvokeDefault on that bar method to call it, passing in whatever value you want for bar as a parameter.
精彩评论