Help Using Javascript Code in a UIWebView

血红的双手。 提交于 2019-12-07 10:13:31

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4585193/help-using-javascript-code-in-a-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!