1

I am trying to run the code below in webview's shouldStartLoadWithRequest delegate method but it doesn't make any changes.

- (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;
}

There is no error, it prints the NSLog and everything in the method works great except "stringByEvaluatingJavaScriptFromString" method.

But if I try to make text bold in another function, for example an IBAction method, works fine.

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

Actually, this is my company's special application and this UIWebView will not show the web pages. I am using it to show some custom HTML pages. I need to make everything in "shouldStartLoadWithRequest" because I am trying to run an objective-c method from javascript.

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)"]];
}

1 Answer 1

2

The doc says that method webView:shouldStartLoadWithRequest: is sent before a web view begins loading a frame. After you return YES in this method, web view starts loading a request. So any javascript you execute will have no effect, because a new page will be loaded after your JS call.

You can probably use webViewDidFinishLoad: method to execute javascript after page finishes to load. Or if you want to trigger JS by clicking on a link, you can use shouldStartLoadWithRequest but return NO from it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.