通过WebScriptObject从Objective-C调用Javascript

时间:2010-02-12 19:03:37

标签: javascript cocoa

我决定通过让我的应用程序向嵌入式webview中的网页提供字符串数据来改变我在Cocoa应用程序中实现打印的方式,然后我将打印该webview / frame。

问题是我的代码没有被调用,我没有看到返回错误。

以下是设置:

1)使用Dashcode并构建网页。生成的文档中没有“表单”容器,但它包含以下字段:

   <input id="customerNameField" type="text" name="" value="">
    <input id="customerStreetField" type="text" name="" value="">

2)在IB中,我创建了一个窗口,在WebView中抛出,将其链接到我的控制器中的插座并创建NSURLRequest,抓取我的WebView的mainFrame并让它加载请求。这工作,页面显示在WebView中。代码:

 [[wv mainFrame] stopLoading];     

 request = [NSURLRequest requestWithURL:currentPrintTemplateURL];

 [[wv mainFrame] loadRequest:request];

3)我想在webView中设置customerNameField的值,所以我执行以下操作:

3A)在我的控制器上使用类方法,允许桥接访问所有键:

+(BOOL)isKeyExcludedFromWebScript:(const char *)name {

 // TODO: Implement specific blocks here; but for now let it all through

 NSLog(@"Excluding nothing from WebScript");

 return NO;

}

3B)在我的HTML文件中添加一个JavaScript函数,我想用Cocoa中的参数调用它:

function populateRepairFields(repairCase) {
 document.getElementById("customerNameField").value = repairCase;
 }

(我知道javascript单行代码有效,因为我可以在页面上添加一个按钮,在onClick中触发函数,代码修改customerNamefield的值。)

3C)向webview询问它的windowScriptObject,创建一个要传递给javascript函数的NSArray参数,然后使用callWebScriptMethod方法执行它们:

     // grab the data we want to send to the javascript     
    NSString *customerFirstName = [self valueForKeyPath:@"currentRepairCase.customer.firstName"];

 NSLog(@"(debug) Ensure we have a value - customerFirstName = %@", customerFirstName);

 // build the array whose items will be passed as arguments to the javascript method

   NSArray * args = [NSArray arrayWithObjects:customerFirstName, nil]; 

// get the windowScriptObject, then (debug) log the output so we can be sure it is not null

  ws = [wv windowScriptObject];


 NSLog(@"WebScriptObject = %@", ws);


//Then call the javascript method via the bridge, logging the output so we can see if there is an WSUndefined error returned (results are the same even if we don't wrap it in an NSLog)

     NSLog(@"WS ERR: %@", [ws callWebScriptMethod:@"populateRepairFields" withArguments:args]);  

4)所有这一切。没别的了。我没有看到被调用的类方法(3A),并且没有获得WSUndefined或任何其他错误消息(3C),如果我尝试在我的代码中添加javascript警报,则看不到警报。

我想也许我需要为WebView设置一个委托,但在检查了文档后,我没有看到WebScript的委托要求。 (然后我将所有代表出口连接到我的控制器,但这没有帮助。)

为什么我的代码似乎没有被调用?有什么遗漏?

谢谢..

1 个答案:

答案 0 :(得分:2)

您只能在WebScriptObject实例准备就绪后使用WebView实例,并且在您致电后WebView实例尚未就绪

 [[wv mainFrame] loadRequest:request];

因为加载是由WebKit自动在后台线程中完成的。 您的代码应该按原样运行,只要您稍后从webview委托,操作方法等调用它。