2010-02-12 44 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代理,操作方法等中調用它即可。