UIWebView注入javascript iphone

本文探讨了UIWebView中使用stringByEvaluatingJavaScriptFromString方法的强大功能,包括执行多行JavaScript代码、注入自定义函数及从HTML文档获取信息等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from: http://www.devdiv.com/thread-31578-1-1.html

UIWebView has very few instance methods. One of them is stringByEvaluatingJavaScriptFromString, which very powerful and unfortunately poorly documented. (This is literally the extent of Apple’s explanation: “Returns the result of running a script.”)


Let’s explore this mysterious method with a couple of examples.

A trivial example of how to use stringByEvaluatingJavaScriptFromString is to get the title of the HTML document:

  1. NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];


You would typically place this line of code in webViewDidFinishLoad.

This technique is not limited to one-liners, or accessing simple properties. Here’s an example of two lines of JavaScript code executed in order, as you would expect:

  1. [webView stringByEvaluatingJavaScriptFromString:@"var field = document.getElementById('field_2');"
  2.                                                  "field.value='Multiple statements - OK';"];



You can also call JavaScript functions this way. And if you want to call a JavaScript function that does not already exist in the web page that you’re downloading, you can “inject” it yourself with this technique:


  1. [webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
  2.                                                  "script.type = 'text/javascript';"
  3.                                                  "script.text = \"function myFunction() { "
  4.                                                         "var field = document.getElementById('field_3');"
  5.                                                         "field.value='Calling function - OK';"
  6.                                                  "}\";"
  7.                                                  "document.getElementsByTagName('head')[0].appendChild(script);"];

  8. [webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];


In essence I’m using Objective C to create a string which represents JavaScript which which when executed adds a JavaScript function to the HTML DOM. Apologies for the multiple meta levels… Let me try to untangle this line by line.

Line 1 : First we create a <script> element using JavaScript.
Line 2 : Set the type of the <script> element to text/javascript.
Line 3-6 : Set the content of the <script> element to the JavaScript function that you want to inject.
Line 7 : Add the new <script> element as a child to the <head> element of the HTML DOM.
Line 9 : Call the new JavaScript function.

Bonus tip: You can break up NSString constants over multiple lines in Xcode for increased readability. Just end the line with a double-quote character and begin the next line with a double-quote character. At compile time these lines will be joined into one string. So the string that begins with “var script” on Line 1 is one continuous string ending with “appendChild(script);” on Line 7.

Although it’s not critical for the discussion above, here’s the HTML that the example JavaScript refers to:



  1. 01.<html>  
  2. 02.  <head>  
  3. 03.    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0"/>  
  4. 04.  </head>  
  5. 05.  <body>  
  6. 06.    <p>This is the UIWebView</p>  
  7. 07.    <form>  
  8. 08.      <input id="field_1" type="text" name="value" /><br/>  
  9. 09.      <input id="field_2" type="text" name="value" /><br/>  
  10. 10.      <input id="field_3" type="text" name="value" /><br/>  
  11. 11.    </form>  
  12. 12.  </body>  
  13. 13.</html>

点击页面上的一个按钮,回调到自己的Objective-c代码了


<html>
<body>
<textarea id="ttt"></textarea> 
<input type="button1"  value="GetSR" onClick="fn()"/>
  <input type="button2"  value="Download" onClick="doDownload()"/>
</body>
</html>


<script>
function fn()
{
       alert("tt");
}


function doDownload()
{
      var url = 'http://192.168.1.2/dj_bmw.mp3';
      iPhone.downloadUrl(url);
}
</script>


页面加载完的时候 调用javascript函数把页面里doDownload代码

  1. function doDownload()
  2. {
  3.      window.locate = '/_Custom_Lint/ var url = http://192.168.1.2/dj_bmw.mp3; iPhone.downloadUrl(url);' 
  4. }
UIWebView回调


  1. - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request 
  2.           navigation:(UIWebViewNavigationType)navigationType
  3. {
  4.       NSString* urlString = [ [request URL] absoluteString] ;
  5.      if (urlString 包含 "/_Custom_Lint")
  6.     {
  7.           解析urlString 取出具体的下载地址( 'http://192.168.1.2/dj_bmw.mp3'),调用本地下载代码。
  8.            return NO;
  9.     }
  10.     return YES;
  11. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值