我可以在Spidermonkey中执行Javascript函数并获取返回值吗? [英] Can I execute a Javascript function inside Spidermonkey and get the return value?
问题描述
我刚刚开始使用Delphi和Spidermonkey。以前我会将一个网页加载到TWebBrowser组件中,并与加载的网页中的Javascript代码进行交互。这很麻烦,因为要将值返回给delphi,我必须通过Javascript代码将它们加载到DOM对象中,然后从Delphi中检查DOM以找到该对象并访问它的 value 属性。
I'm just getting into using Delphi with Spidermonkey. Previously I would load a web page into a TWebBrowser component and interact with the Javascript code in the loaded web page. This was messy because to return values back to delphi I had to load them into a DOM object via the Javascript code and then inspect the DOM from Delphi to find that object and access it's value property.
使用Spidermonkey,我可以执行特定的Javascript函数并轻松获取返回值并直接返回Delphi吗?如果是这样,请指出一个有用的快速代码示例。 Spidermonkey附带的3个样本似乎没有进入这个。
With Spidermonkey, can I execute a specific Javascript function and get the return value easily and directly back into Delphi? If so, please point me to a quick code example that would be helpful. The 3 samples that came with Spidermonkey don't seem to get into this.
推荐答案
>使用Spidermonkey,我可以吗?执行一个特定的Javascript函数并轻松获得返回值并直接返回Delphi?
是的,这是可能的。示例与Delphi XE2 / XE4兼容。
Yes, it possible. Sample compatible with Delphi XE2/XE4.
var
recFunction,
recReturnValue,
recJSVar : jsval;
........
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=- Find entry point to function.
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
if JS_LookupProperty (TSMJSEngine.Context, TSMJSEngine.Global.JSObject, PAnsiChar (AnsiString (strFunctionToRun)), @recFunction) <> js_true then
begin
//-=- Everything very bad :)
end;
if recFunction.asPtr = nil then
begin
//-=- Everything very bad :)
end;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=- Call function
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
if JS_CallFunctionValue (TSMJSEngine.Context, TSMJSEngine.Global.JSObject, recFunction, 0, nil, @recReturnValue) = Integer (false) then
begin
//-=- Everything very bad :)
end;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=- Get returning result (type: string).
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
strResult := JSValToString (TSMJSEngine.Context, recReturnValue);
这篇关于我可以在Spidermonkey中执行Javascript函数并获取返回值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!