WebView OC与js交互

Demo

ViewController

import WebKit/WebKit.h
import “EasyJSWebView.h”
import “TQInterface.h”

////WKWebView

@interface ViewController ()
- (IBAction)click:(id)sender;

@property (nonatomic,strong) EasyJSWebView *webView;

@end

@implementation ViewController

//html —> URL
//html —> json 一部分

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.webView = [[EasyJSWebView alloc] initWithFrame:self.view.bounds];

    TQInterface *inter = [[TQInterface alloc] init];

    //WithName js中要调用oc的方法 必须拿到该参数
    [self.webView addJavascriptInterfaces:inter WithName:@”testName”];

    NSString *path = [[NSBundle mainBundle] pathForResource:@”test” ofType:@”html”];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];

    //[self.webView loadHTMLString:@”html数据” baseURL:nil];

    [self.view addSubview:self.webView];

    [self.view sendSubviewToBack:self.webView];

    //OC 和 jS交互

}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

  • (IBAction)click:(id)sender {

    NSLog(@”%@”,[self.webView stringByEvaluatingJavaScriptFromString:@”buttonClick()”]);
    }
    @end

TQInterface.m

@implementation TQInterface

-(void)testFunc
{
NSLog(@”%@”,NSStringFromSelector(_cmd));
}

-(void)testFunc1:(NSString *)name
{
NSLog(@”%@ —> %@”,NSStringFromSelector(_cmd),name);
}

@end

test.html

!DOCTYPE html>
html>
head>
meta charset=”UTF-8”>
title>/title>

    style type="text/css">
        /*css样式*/
        /*标签名{}*/
        /*p{
            color: red;
            font-size: 24px;
            background: chartreuse;
        }*/
        /*id选择器*/
        /*#red{
            color: red; 
        }

        #blue {
            color: blue;
        }*/

        /*类选择器*/
        .clsRed{
            color: red;
        }

        .clsBlue{
            color: blue;
        }

    /style>

    !--js  swift-->
    script type="text/javascript">  
        function buttonClick()
        {

// 弹出框
//alert(“click”);
//document.getElementById(“blue”).hidden = true;

// return “123”;
testName.testFunc();
testName.testFunc1(“js 传参”);
}
/script>
/head>
body>

    h1>一级标题/h1>
    p id="red" class="clsRed">啥地方拿数据库费那事了开发那/p>
    p id="blue" class="clsBlue">asfdasfasfasfafa/p>
    h2>一级标题/h2>
    h3>一级标题/h3>
    h4>一级标题/h4>
    h5>一级标题/h5>

    !--超链接   a -->  
    a href="http://www.baidu.com">百度/a>

    !--图片  img-->
    img src="/img/HBuilder.png"/>

    !--按钮  input   事件必须使用 js 代码-->
    input type="button" value="按钮" onclick="buttonClick()"/>
/body>

/html>

猜你喜欢

转载自blog.csdn.net/weixin_35966617/article/details/53083450