开发者

QtWebkit: how to send an exception from Qt to the JavaScript context?

I have a simple Qt 4.7 application that uses QtWebKit to display a HTML/JavaScript page. Using addToJavaScriptWindowObject() a few C++ functions are provided to the JavaScript environment.

Is there a way to raise an exception in the JavaScript context in certain situations when such a function is called from JavaScript?

  • Throwing a C++ exception, like throw 123;, simply crashes the Qt application
  • Using evaluateJavaScript("throw new Error('whatever');") I can throw an exception but apparently it is not being passed to the calling JavaScript context (i.e. just the eval() code itself is being aborted)

Looking at the source code I see methods like setException()开发者_JAVA技巧 and similar but apparently I need a JSContext or some other reference to the calling JavaScript context, but I have no clue how to get it (there is no such thing in QWebFrame although WebKit itself or QWebFramePrivate seem to have such a reference.

My final goal is that a JavaScript code like

try {
  specialBrowserObject.someFunction();
} catch (e) {
  document.write("Exception: "+e.message);
}

shows the exception created in C++ (specialBrowserObject being the object exposed via addToJavaScriptWindowObject()).

Any ideas?


As far as I've been able to tell, it isn't possible to throw an exception from C++ to be caught in JavaScript. I can suggest a few workarounds but these may, or may not, be suitable solutions for you. I realise that neither is the perfect solution you were hoping for.

1) Use a Q_PROPERTY so that the C++ code can set a value if it wants to cause an exception on return to the JavaScript. The JavaScript would have to check the value to see if an exception is required upon return from the C++ function and then throw one manually.

2) Along the same lines, but slightly neater in my opinion, would be to use a Q_INVOKABLE function that returns a QString to your JavaScript. If the string isn't empty, throw an exception from JavaScript.

The function would be defined in the header file as -

Q_INVOKABLE QString someFunction( int divisor );

The function would be something along these lines in the main cpp file -

QString className::someFunction( int divisor ) {
  // Main body of function doing various things
  ...
  ...
  // Do we need to throw an exception?
  if( divisor == 0 )
    return "Divide by zero";
  ...
  ...
  // Function has succeeded so no need to throw an exception
  return "";
}

The JavaScript would look something like this -

try {
  retVal = specialBrowserObject.someFunction( divisor );
  if( retVal != "" )
    throw new Error( retVal );
} catch (e) {
  document.write("Exception: "+e.message);
}

I hope this is of some help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜