July 9, 2007

Getting/Setting JavaScript variables with WebKit

Filed under: Distribute — Ryan Wilcox @ 8:53 pm

Further progress on the WebKit front. I’m working with Kevin Ollivier, the author of wxWebKit, to put C++ to JavaScript utilities into the framework itself. Right now this is focused mostly on calling JavaScript functions from C++, and translating C++ values into JSValues, but I suspect other things will come from this as well.

For example, this weekend (along with some C++ interface structuring) I was looking at my JavaScript function calling code and found something. Specifically, how to get and set JavaScript variables from C++. Not exactly what I was looking for, but very useful none-the-less.

void PutJSValue(const std::string& memberName, KJS::JSValue* val)  
{
WebCore::KJSProxy* js = m_frame->scriptProxy();
KJS::ScriptInterpreter* interp = js->interpreter();
KJS::ExecState* exec = interp->globalExec();
//TODO: error checking ASSERT(!exec->hadException()); 
KJS::JSLock lock;
//look up the object 
KJS::JSValue* JSMemberName = KJS::jsString( memberName.c_str() );
KJS::Identifier identifier( JSMemberName->toString(exec) );
KJS::JSObject* rootObj = interp->globalObject();
rootObj->put(exec, identifier, val);
if ( exec->hadException() )
{
KJS::JSValue* theEx = exec->exception();
//TODO: figure out how to convert UString to a wxString 
//use JSValue.toString() gives us a UString 
throw RuntimeJSError("Error while setting value in JavaScript");
}
}

There are still some things to do, of course. First, the matter of capturing exception information from JavaScript. Secondly, I don’t know if this method supports setting object members: say window.document.baseURI. I can access window.something, but I don’t know about anything more complex. Right now I’m not going to worry about it.

Next up: converting C++ values into JavaScript values (and back). Someday I will get to calling C++ functions from JavaScript…

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment