【发布时间】:2010-02-13 09:31:14
【问题描述】:
我决定改变我在 Cocoa 应用程序中实现打印的方式,让我的应用程序向嵌入式 webview 中的网页提供字符串数据,然后我会打印该 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,创建一个 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 的委托要求。 (然后我将所有的代表插座连接到我的控制器,但这没有帮助。)
为什么我的代码似乎没有被调用?缺少什么?
谢谢..
【问题讨论】:
-
嗯...我制作了一个示例应用程序并复制了您的代码,它可以正常工作。从哪里执行步骤 3C?我唯一能想到的是你在 webview 准备好之前调用了 3C。 (URL 加载需要一些事件周期,即使它是本地文件。)我从附加到 NSButton 的 IBAction 调用它。
-
谢谢你,宇治。这就是问题所在。我将 Javascript 调用移至在框架完成加载后调用的 WebView 委托方法,从而确保 webview 已准备就绪。有用。耶!使用的委托://在第 2 步的最后一行之前添加:[wv setFrameLoadDelegate:self]; // 包含来自 3C 的所有代码: - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame;
标签: javascript cocoa