zoukankan      html  css  js  c++  java
  • OS开发之Objective-C与JavaScript的交互

    UIWebView是iOS最常用的SDK之一,它有一个stringByEvaluatingJavaScriptFromString方法可以将javascript嵌入页面中,通过这个方法我们可以在iOS中与UIWebView中的网页元素交互。

    stringByEvaluatingJavaScriptFromString

        使用stringByEvaluatingJavaScriptFromString方法,需要等UIWebView中的页面加载完成之后去调用。我们在界面上拖放一个UIWebView控件。在Load中将google mobile加载到这个控件中,代码如下:

    复制代码
    - (void)viewDidLoad
    {
    [super viewDidLoad];
    webview.backgroundColor = [UIColor clearColor];
    webview.scalesPageToFit =YES;
    webview.delegate =self;
    NSURL *url =[[NSURL alloc] initWithString:@"http://www.google.com.hk/m?gl=CN&hl=zh_CN&source=ihp"];

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    [webview loadRequest:request];
    }
    复制代码

    我们在webViewDidFinishLoad方法中就可以通过javascript操作界面元素了。

    1、获取当前页面的url。

    - (void)webViewDidFinishLoad:(UIWebView *)webView {  
    NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    }

    2、获取页面title:

    - (void)webViewDidFinishLoad:(UIWebView *)webView {  
    NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];

    NSString *title = [webview stringByEvaluatingJavaScriptFromString:@"document.title"];
    }

    3、修改界面元素的值。

        NSString *js_result = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('q')[0].value='朱祁林';"];

    4、表单提交:

            NSString *js_result2 = [webView stringByEvaluatingJavaScriptFromString:@"document.forms[0].submit(); "];

    这样就实现了在google搜索关键字:“朱祁林”的功能。

    5、插入js代码

    上面的功能我们可以封装到一个js函数中,将这个函数插入到页面上执行,代码如下:

    复制代码
             [webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"  
    "script.type = 'text/javascript';"
    "script.text = "function myFunction() { "
    "var field = document.getElementsByName('q')[0];"
    "field.value='朱祁林';"
    "document.forms[0].submit();"
    "}";"
    "document.getElementsByTagName('head')[0].appendChild(script);"];

    [webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];
    复制代码

    看上面的代码:

    a、首先通过js创建一个script的标签,type为'text/javascript'。

    b、然后在这个标签中插入一段字符串,这段字符串就是一个函数:myFunction,这个函数实现google自动搜索关键字的功能。

    c、然后使用stringByEvaluatingJavaScriptFromString执行myFunction函数。

  • 相关阅读:
    跨域资源共享 CORS 详解以及IIS中的配置方法
    c#创建文件夹时无法访问路径,路径拒绝访问
    C#接口在派生类和外部类中的调用
    .NET/C#识别用户访问设备
    另一个SqlParameterCollection中已包含SqlParameter
    Java中throw和throws的区别
    MySQL与Oracle的语法区别详细对比
    hibernte中用criteria实现not in功能的方法
    使用Hibernate SQLQuery执行原生SQL
    hibernate查询数据表char类型字段只返回一个字符
  • 原文地址:https://www.cnblogs.com/HMJ-29/p/5407571.html
Copyright © 2011-2022 走看看