2010-02-12 41 views
1

我决定改变我在Cocoa应用程序中实现打印的方式,让我的应用程序向嵌入式webview中的网页提供字符串数据,然后打印该webview /框架。通过WebScriptObject从Objective-C调用Javascript

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

这里是设置:

1)使用Dashcode并建立一个网页。还有就是生成的文档中没有“形式”的容器,但它有这样的字段:

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

2)在IB,我创建了一个窗口,抛在网页视图,它在我的控制器连接到插座和创建一个NSURLRequest,抓住我的WebView的mainFrame并让它加载请求。这工作,该页面显示在WebView中。代码:

[[wv mainFrame] stopLoading];  

request = [NSURLRequest requestWithURL:currentPrintTemplateURL]; 

[[wv mainFrame] loadRequest:request]; 

3)我想设置customerNameField的价值在我的web视图,所以我做到以下几点:

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)JavaScript函数添加到我的HTML文件,我想从可可带参数调用:

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

(我知道javascript单行代码的作品,因为我可以在我的页面上添加一个按钮,在onClick中触发该功能并且代码修改了customerName字段的值。)

3C)询问webview它是windowScriptObject,创建的参数一个NSArray传递给JavaScript函数,然后使用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

嗯...我做了一个示例应用程序并复制了您的代码,并且它没有任何问题。你从哪里进行3C步骤?我能想到的唯一的事情就是在webview准备好之前你已经调用了3C。 (URL加载需要一些事件周期,即使它是本地文件。)我从附加到NSButton的IBAction中调用它。 – Yuji 2010-02-12 22:49:49

+0

谢谢Yuji。这是问题所在。我将Javascript调用移出到WebView委托方法,该方法在框架加载完成后调用,从而确保webview已准备就绪。有用。好极了! 使用的代表: //在步骤2的最后一行之前添加: \t [wv setFrameLoadDelegate:self]; //包含3C的所有代码: - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame; – Woodster 2010-02-13 00:55:39

回答

2

后,才能在WebView实例准备好使用WebScriptObject实例和WebView实例不是

[[wv mainFrame] loadRequest:request]; 

因为负荷在做你的电话后,准备右后台线程由WebKit自动完成。 您的代码应该按原样工作,只要您之后从webview代理,操作方法等中调用它即可。