2013-07-15 42 views
1

我想在webview的shouldStartLoadWithRequest委託方法中運行下面的代碼,但它不作任何更改。shouldStartLoadWithRequest不運行stringByEvaluatingJavaScriptFromString方法

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ 
    NSLog(@"webView shouldStartLoadingWithRequest"); 
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.execCommand('bold', false,null)"]]; 
    return TRUE; 
} 

沒有錯誤,它打印的NSLog和除「stringByEvaluatingJavaScriptFromString法」 一切都在方法的偉大工程。

但是,如果我嘗試在另一個函數中使文本變爲粗體,例如一個IBAction方法,可以正常工作。

-(IBAction)boldClick:(id)sender 
{ 
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.execCommand('bold', false,null)"]]; 
} 

其實,這是我公司的特殊應用,這UIWebView中不會顯示網頁。我用它來顯示一些自定義的HTML頁面。 我需要在「shouldStartLoadWithRequest」中做所有事情,因爲我試圖從javascript運行一個Objective-C方法。

UPDATE

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ 

    // Break apart request URL 
    NSString *requestString = [[request URL] absoluteString]; 
    NSArray *components = [requestString componentsSeparatedByString:@":"]; 


    // Check for your protocol 
    if ([components count]==3) 
    { 
     [self makeBoldText]; 
     return NO; 
    } 
    else 
    { 
     return TRUE; 
    } 
} 

-(void)makeBoldText 
{ 
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.execCommand('bold', false,null)"]]; 
} 

回答

2

的醫生說該方法webView:shouldStartLoadWithRequest:被之前發送網絡視圖開始加載的幀。在此方法中返回YES後,Web視圖開始加載請求。因此,您執行的任何JavaScript都將不起作用,因爲您的JS調用將在之後加載一個新頁面

您可以使用webViewDidFinishLoad:方法在頁面加載完成後執行javascript。或者如果你想通過點擊一個鏈接來觸發JS,你可以使用shouldStartLoadWithRequest,但是從它返回NO。

相關問題