iOS与JavaScript交互二: JavaScriptCor

2018-02-14  本文已影响28人  Carson_Zhu

简介

iOS 7.0开始,iOS加入了JavaScriptCore框架。用Objective-CWebKitJavaScript引擎封装了一下,提供了简单快捷的方式与JavaScript交互。

JavaScriptCore使用

NSHipster中文版的Java​Script​Core
iOS7 新JavaScriptCore框架入门介绍

简要介绍JavaScriptCore

#ifndef JavaScriptCore_h
#define JavaScriptCore_h

#include <JavaScriptCore/JavaScript.h>
#include <JavaScriptCore/JSStringRefCF.h>

#if defined(__OBJC__) && JSC_OBJC_API_ENABLED

#import "JSContext.h"
#import "JSValue.h"
#import "JSManagedValue.h"
#import "JSVirtualMachine.h"
#import "JSExport.h"

#endif
#endif /* JavaScriptCore_h */

JavaScriptCore.h中可以看到,该框架主要的类就只有五个:

JSVirtualMachine

看名字直译是JS虚拟机,也就是说JavaScript是在一个虚拟的环境中执行,而JSVirtualMachine为其执行提供底层资源。

/*!
@interface
@discussion An instance of JSVirtualMachine represents a single JavaScript "object space"
 or set of execution resources. Thread safety is supported by locking the
 virtual machine, with concurrent JavaScript execution supported by allocating
 separate instances of JSVirtualMachine.
*/
NS_CLASS_AVAILABLE(10_9, 7_0)
@interface JSVirtualMachine : NSObject

翻译这段描述:

一个JSVirtualMachine实例,代表一个独立的JavaScript对象空间,并为其执行提供资源。它通过加锁虚拟机,保证JSVirtualMachine是线程安全的,如果要并发执行JavaScript,那我们必须创建多个独立的JSVirtualMachine实例,在不同的实例中执行JavaScript

但是我们一般不用新建JSVirtualMachine对象,因为创建JSContext时,如果我们不提供一个特性的JSVirtualMachine,内部会自动创建一个JSVirtualMachine对象。

JSContext

JSContext是为JavaScript的执行提供运行环境,所有的JavaScript的执行都必须在JSContext环境中。JSContext也管理JSVirtualMachine中对象的生命周期。每一个JSValue对象都要强引用关联一个JSContext。当与某JSContext对象关联的所有JSValue释放后,JSContext也会被释放。

// 1.这种方式需要传入一个JSVirtualMachine对象,如果传nil,会导致应用崩溃的。
JSVirtualMachine *JSVM = [[JSVirtualMachine alloc] init];
JSContext *JSCtx = [[JSContext alloc] initWithVirtualMachine:JSVM];

// 2.这种方式,内部会自动创建一个JSVirtualMachine对象,可以通过JSCtx.virtualMachine
// 看其是否创建了一个JSVirtualMachine对象。
JSContext *JSCtx = [[JSContext alloc] init];

// 3. 通过webView的获取JSContext。
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

上面推荐的两篇文章以及网上介绍JavaScriptCore的文章多是通过1和2这两种方式创建JSContext,然后执行JavaScript,演示JavaScriptCore。我一直有疑问,如果不是HTML结合UIWebView,才会使用到JavaScript,那在一个虚拟的环境里运行JS有什么意义。所以,后面我是用方式3来创建JSContext

JSValue

JSValue都是通过JSContext返回或者创建的,并没有构造方法。JSValue包含了每一个JavaScript类型的值,通过JSValue可以将Objective-C中的类型转换为JavaScript中的类型,也可以将JavaScript中的类型转换为Objective-C中的类型。

JSManagedValue

JSManagedValue主要用途是解决JSValue对象在Objective-C堆上的安全引用问题。把JSValue保存进Objective-C堆对象中是不正确的,这很容易引发循环引用,而导致JSContext不能释放。

JSExport

JSExport是一个协议类,但是该协议并没有任何属性和方法。我们可以自定义一个协议类,继承自JSExport。无论我们在JSExport里声明的属性,实例方法还是类方法,继承的协议都会自动的提供给任何JavaScript代码。我们只需要在自定义的协议类中,添加上属性和方法就可以了。

使用

本地HTML
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script>
        function loadURL(url) {
            var iFrame;
            iFrame = document.createElement("iframe");
            iFrame.setAttribute("src", url);
            iFrame.setAttribute("style", "display:none;");
            iFrame.setAttribute("height", "0px");
            iFrame.setAttribute("width", "0px");
            iFrame.setAttribute("frameborder", "0");
            document.body.appendChild(iFrame);
            // 发起请求后这个iFrame就没用了,所以把它从dom上移除掉
            iFrame.parentNode.removeChild(iFrame);
            iFrame = null;
        }

        function asyncAlert(content) {
            setTimeout(function(){
                alert(content);
            },1);
        }
        
        function showAlertClick() {
            showAlert();
        }
        
        function alertWithString(content) {
            asyncAlert(content);
            document.getElementById("returnValue").value = content;
        }
        
        function callMethodClick() {
            setColor();
        }
        
        function callMethodWithObjectClick() {
            bridge.setColorWithRGB(20, 180, 250, 0.5);
        }

    </script>
</head>
<body>

    <input type="button" value="OC调用JS" onclick="showAlertClick()">
    <input type="button" value="JS直接调用OC" onclick="callMethodClick()">
    <input type="button" value="JS通过对象调用OC" onclick="callMethodWithObjectClick()">

</body>
</html>
加载WebView
- (void)loadWebView {
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    self.webView.delegate = self;
    
    NSURL *indexURL = [[NSBundle mainBundle] URLForResource:@"index1" withExtension:@"html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:indexURL];
    [self.webView loadRequest:request];
    [self.view addSubview:self.webView];
}
获取JSContext

实现UIWebViewDelegate协议方法- (void)webViewDidFinishLoad:(UIWebView *)webView

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    [self showAlertWithContext:context];
    [self setColorWithContext:context];
    [self setColorByInterfaceWithContext:context];
}
OC调用JS
[context evaluateScript:@"alertWithString('OC调用JS方法')"];
- (void)showAlertWithContext:(JSContext *)context {
    context[@"showAlert"] = ^(){
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *jsStr = [NSString stringWithFormat:@"alertWithMessage('%@')", @"OC调用JS方法"];
            [self.webView stringByEvaluatingJavaScriptFromString:jsStr];
        });
    };
}
JS调用OC
- (void)setColorWithContext:(JSContext *)context {
    context[@"setColor"] = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIColor *color = [UIColor colorWithRed:arc4random()%256/255.0f green:arc4random()%256/255.0f blue:arc4random()%256/255.0f alpha:0.5];
            self.navigationController.navigationBar.backgroundColor = color;
        });
    };
}
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>

@protocol JSBridge <JSExport>

// - (void)goURL:(NSString *)URL; 一个参数
// 当方法有两个或两个以上参数时,OC方法与JS方法保持一致
JSExportAs(setColorWithRGB, - (void)setColorWithRGB:(int)red green:(int)green blue:(int)blue alpha:(double)alpha);

@end

Controller遵守协议实现方法。

- (void)setColorWithRGB:(int)red green:(int)green blue:(int)blue alpha:(double)alpha {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIColor *color = [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha];
        self.navigationController.navigationBar.backgroundColor = color;
    });
}

JSContext注册对象:

- (void)setColorByInterfaceWithContext:(JSContext *)context {
    // 当前JSContext注册对象
    context[@"bridge"] = self;
}
效果

WKWebView与JavaScriptCore

由于WKWebView不支持通过如下的KVC的方式创建JSContext,所以WKWebView中如何实现OCJS交互可以看前面这篇文章iOS与JavaScript交互三: MessageHandler

上一篇 下一篇

猜你喜欢

热点阅读