• 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函数。

  • 相关阅读:
    JVM中java类的加载时机(转载:http://blog.csdn.net/chenleixing/article/details/47099725)
    自定义filter包
    Tomcat中Listener的使用范例(转载http://cywhoyi.iteye.com/blog/2075848)
    Quartz简单使用
    PAT A1119 Pre- and Post-order Traversals [前序后序求中序]
    PAT A1115 Counting Nodes in a BST [二叉搜索树]
    PAT A1110 Complete Binary Tree [完全二叉树]
    PAT A1102 Invert a Binary Tree [反转二叉树]
    PAT A1099 Build A Binary Search Tree [二叉搜索树]
    PAT A1094 The Largest Generation [树的遍历]
  • 原文地址:https://www.cnblogs.com/HMJ-29/p/5407571.html
Copyright © 2020-2023  润新知