4

I would like to run the following code in a webView, so that the content is editable:

javascript: document.body.contentEditable ='true'; document.designMode='on'; void 0

So far I have got as far as trying this:

- (void)webViewDidFinishLoad:(UIWebView *)webViews  
{    
    NSString *string = @"javascript: document.body.contentEditable ='true'; document.designMode='on'; void 0";
    [webView stringByEvaluatingJavaScriptFromString:string];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:string]]];
    NSLog(@"finished load");
}

If you could tell me how to get this working that would be great.

Greg
  • 10,360
  • 6
  • 44
  • 67
MKDev
  • 147
  • 2
  • 12

2 Answers2

2

I like wrapping up my JavaScript calls in JavaScript. What I mean by this is, if there are multiple lines to be run in JavaScript, to wrap that in a function and call just the function. This separates the logic out cleanly and let's you test things strictly in Safari without building an iPhone app around it.

Also, I agree with what Evan said about getting rid of the [webView loadRequest:.

EDIT: By wrapping up, I mean something like:

function foo() { document.body.contentEditable ='true'; document.designMode='on'; }

And then just calling "foo" in your call from iOS.

donkim
  • 13,119
  • 3
  • 42
  • 47
  • thanks.. one more thing how can I call it, and would I put it like this: [webView stringByEvaluatingJavascriptFromString:"function foo() { document.body.contentEditable ='true'; document.designMode='on'; }"]; [webView stringByEvaluatingJavascriptFromString:foo]; – MKDev Jan 05 '11 at 02:24
  • You would have the function I wrote in your HTML file. That way, you can test that your code works in a browser, as opposed to an app, and, when you're sure it works, you could then have the iPhone call it. You would call it in iOS by doing: `[webView stringByEvaluatingJavascriptFromString:@"foo()"]` – donkim Jan 05 '11 at 02:37
  • oh I am not using an html file – MKDev Jan 05 '11 at 02:39
  • Oh... so you want to call this on any HTML you load in the `UIWebView`, huh, not necessarily something you create yourself. My apologies. :) – donkim Jan 05 '11 at 02:41
0

Remove the JavaScript: prefix. That method already knows that you will be evaluating JavaScript, so there is no need for redundancy.

Also, don't send that request at the end. Evaluating using that method will execute it on the current page.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144