2013-10-21 28 views
0

我有一個UIWebView,其中一些JavaScript也正在執行。當我們點擊第一個按鈕時,它正確地執行了JavaScript代碼並且完美地工作,但是當我們點擊任何其他按鈕然後導航回到舊視圖時,JavaScript不起作用。以下是我的代碼。UIWebView在iOS中執行JavaScript時顯示錯誤

- (void)webViewDidStartLoad:(UIWebView *)webView { 
    NSMutableString *javascriptFunctions = [NSMutableString stringWithString:@"var t3 = new function() { this.setTitle = function(text) { window.location.href = 'about:title:' + encodeURIComponent(text); }; "]; 
    [javascriptFunctions appendString:@"this.setAppointment = function(beginTime, endTime, title, description, isUTC) { window.location.href = 't3://web-command/calendar?beginTime=' + encodeURIComponent(beginTime) + '&endTime=' + encodeURIComponent(endTime) + '&title=' + encodeURIComponent(title) + '&description=' + encodeURIComponent(description) + '&isUTC=' + encodeURIComponent(isUTC); }; "]; 
    [javascriptFunctions appendString:@"this.setBackButtonVisibility = function(isVisible) { window.location.href = 'about:back:' + encodeURIComponent(isVisible); }; "]; 
    [javascriptFunctions appendString:@"this.getBack = function() { window.history.back(); }; "]; 
    [javascriptFunctions appendString:@"this.close = function() { window.location.href = 'about:close'; }; }"]; 

    [self.webView stringByEvaluatingJavaScriptFromString:javascriptFunctions]; 
} 


- (BOOL)webView:(UIWebView *)currentWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { 
    if ([[request.URL.scheme lowercaseString] isEqualToString:@"tel"]) { 
     return YES; 
    } 

    NSString* url = [request.URL.absoluteString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 

    if (url == nil) { 
     [self backToMainScreen]; 
    return NO; 
    } 
} 

回答

0

在UIWebView完全加載網頁之前,Javascript函數不會調用。所以在委託方法webViewDidFinishLoad中調用了所有的JavaScript函數。

- (void)webViewDidFinishLoad:(UIWebView *)webView { 

    NSMutableString *javascriptFunctions = [NSMutableString stringWithString:@"var t3 = new function() { this.setTitle = function(text) { window.location.href = 'about:title:' + encodeURIComponent(text); }; "]; 
    [javascriptFunctions appendString:@"this.setAppointment = function(beginTime, endTime, title, description, isUTC) { window.location.href = 't3://web-command/calendar?beginTime=' + encodeURIComponent(beginTime) + '&endTime=' + encodeURIComponent(endTime) + '&title=' + encodeURIComponent(title) + '&description=' + encodeURIComponent(description) + '&isUTC=' + encodeURIComponent(isUTC); }; "]; 
    [javascriptFunctions appendString:@"this.setBackButtonVisibility = function(isVisible) { window.location.href = 'about:back:' + encodeURIComponent(isVisible); }; "]; 
    [javascriptFunctions appendString:@"this.getBack = function() { window.history.back(); }; "]; 
    [javascriptFunctions appendString:@"this.close = function() { window.location.href = 'about:close'; }; }"]; 

    [self.webView stringByEvaluatingJavaScriptFromString:javascriptFunctions]; 



    }