javaScriptCore 笔记

文档地址:

https://developer.apple.com/documentation/javascriptcore

1Evaluate JavaScript programs from within an app, and support JavaScript scripting of your app.

app里面对javaScript项目求值,支持你的项目的java脚本。

2、The JavaScriptCore Framework provides the ability to evaluate JavaScript programs from within Swift, Objective-C, and C-based apps. You can use also use JavaScriptCore to insert custom objects to the JavaScript environment.

javaScriptCore 框架提供能力从基于swift、oc或者c内部的app去评估javaScript项目,你也能用javaScriptCorejavascript环境插入定制的对象。

3、JSContext

A JSContext object represents a JavaScript execution environment

一个JSContext 对象代表一个javaScript执行环境。

You create and use JavaScript contexts to evaluate JavaScript scripts from Objective-C or Swift code, to access values defined in or calculated in JavaScript, and to make native objects, methods, or functions accessible to JavaScript

你创建和使用javaScript contexts来评估来自oc或者swift代码的javaScript 脚本,用来接近在javaScript定义或者计算的值,使得native的对象、方法、函数能接近javaScript.

4、JSManagedValue

A JSManagedValue object wraps a JSValue object, adding “conditional retain” behavior to provide automatic memory management of values.

一个managedValue对象包裹一个jsValue对象,增加有条件的持有行为,给值提供自动内存管理。

5、The primary use case for a managed value is to store a JavaScript value in an Objective-C or Swift object that is itself exported to JavaScript

管理值基本的使用是存取一个在oc或者swift对象的javaScript值,这个值也是这个管理器传输出给javaScript的。

6、jsValue

A JSValue instance is a reference to a javaScript value.

一个jsValue 实例是对一个java value 的索引。

7、You use the JSValue class to convert basic values (such as numbers and strings) between JavaScript and Objective-C or Swift representations in order to pass data between native code and JavaScript code. 

你使用一个jsValue类在javaScriptoc或者swift代表转换基本的值,确保native code 和javaScript code间能传递数据。

8、You can also use this class to create JavaScript objects that wrap native objects of custom classes or JavaScript functions whose implementations are provided by native methods or blocks.

你也能使用这个类来创建javaScript对象,这些对象包裹定制类的native 对象或者javaScript 函数,这些函数的实现被native 方法或者block提供。

9、classJSVirtualMachine

A JSVirtualMachine instance represents a self-contained environment for JavaScript execution

一个JSVirtualMachine实例代表一个javaScript 执行的独立的环境。

10、You use this class for two main purposes: to support concurrent JavaScript execution, and to manage memory for objects bridged between JavaScript and Objective-C or Swift.

你使用这个类为两个主要的目的:1、支持并发的javaScript执行2、管理在javaScript 和oc或者swfit 桥对象的内存。

11、protocol JSExport 

The protocol you implement to export Objective-C classes and their instance methods, class methods, and properties to JavaScript code.

你实现传输你的oc类和他们实例方法、类方法属性到javaScript 代码的协议

JSContext learning 

12、init!(virtualMachine: JSVirtualMachine!)

Creates a new JavaScript context associated with a specific virtual machine.

创建一个javaScript context,并将这个context与一个特别的虚拟的机器关联起来。

13、By default, each context has an independent virtual machine (a

JSVirtualMachine

object).

默认上,每块画布都有一个独立的虚拟机器(备注:是一个虚拟机器对象)

14、You cannot pass JavaScript values between contexts in different virtual machines.

你不能在不同的机器在画布间传递javaSript值。

15Use this initializer to create a context that shares its virtual machine with other JavaScript contexts to allow passing

JSValue

objects between those contexts.

利用这个初始器来创建一块画布,这个画布跟其他的虚拟的画布分享一个虚拟的机器,这样便于在这些画布间传递javalue值。

16、funcevaluateScript(String!)

Executes the specified JavaScript code

计算特定的javaScript code

17、funcevaluateScript(String!,withSourceURL: URL!)

Executes the specified JavaScript code, treating the specified URL as its source location.

计算特定的javaScript code ,指定特定的url作为它的源位置。

18class funccurrentArguments()

Returns the arguments to the current native callback from JavaScript code.

返回从javaScript代码里对目前native回调的参数。

19funcsetObject(Any!,forKeyedSubscript: (NSCopying & NSObjectProtocol)!)

Sets the specified JavaScript property of the context’s global object, allowing subscript setter syntax.

设置画布全局对象的指定的javaScript 属性,可以使用下标设置器语法。

jsManagedValue learning

20Do not store a non-managedJSValueobject in a native object that is exported to JavaScript. Because aJSValueobject references its enclosingJSContextobject, this action creates a retain cycle, keeping the context from being deallocated.

不要在native对象中存取非管理的要传给javaScript的jsvalue对象,因为一个jsvalue对象引用它的封闭的jsContext 对象,这个行动将会创建一个引用循环,会让这个context不被释放。

21、A managed value’s “conditional retain” behavior ensures that its underlying JavaScript value is retained as long as either of the following conditions is true

只要下面的情形的任何一个是真实的,一个管理值得条件引用的行为能确保这个潜在的java值被引用。

22、The JavaScript value is reachable through the JavaScript object graph (that is, not subject to JavaScript garbage collection)

javaScript 值是可到达的

is subject to 受支配

reachable through 通过

garbage collection 垃圾机制

23TheJSManagedValue object is reachable through the Objective-C or Swift object graph, as reported to the JavaScriptCore virtual machine using theaddManagedReference(_:withOwner:)method

这个管理对象

24However, if neither of these conditions are true, the managed value sets its value property tonil, releasing the underlying JSValue object.

如果这些条件的没有一个是对的,那么这个管理的值设置他的值属性为nil,释放了潜在的jsvalue对象。

25、On its own, a JSManagedValue object behaves similarly to an ARC weak reference to its underlying JSValue object—that is, if you do not use the addManagedReference(_:withOwner:)method to add “conditional retain” behavior, the managed value’s value

property automatically becomes nil when the JavaScript garbage collector destroys the underlying JavaScript value.

从这个类自己角度看,一个JSManagedValue对象表现就像一个对jsValue对象的弱引用,如果你没有使用addManagedReference方法来增加条件引用的行为,这个管理值的值属性在垃圾机制毁坏这个潜在的javaScript value后,自动的变为nil

JSValue JSContext

1、Each JSValue instance originates from a JSContext object that represents the JavaScript execution environment containing that value.

每一个JSValue实例都来源于一个JSContext对象,这个context对象代表包含那个值的java执行环境。

2、The value holds a strong reference to its contextobject—as long as any value associated with a particularJSContext instance is retained, that context remains alive. 

这个值对context对象有一个强引用,只要与这个context实例有关联的任何值被持有,这个context就会保持活跃。

3、When you invoke an instance method is invoked on aJSValue object, and that method returns anotherJSValue object, the returned value belongs to the same context as original value.

当你唤起一个实例的时候,一个实例方法被唤醒作为一个JSValue对象,而那个方法返回另一个jsValue值,这个返回的值属于跟原始值相同的context.

4、Each JavaScript value is also associated (indirectly via thecontextproperty) with a specific JSVirtualMachineobject representing the underlying set of execution resources for its context.

每一个javaScript 值与一个特殊的JSVirtualMachine object相关联,这个JSVirtualMachine object代表为这个context的执行源的潜在的设置。

5 、You can pass JSValue instances only to methods onJSValue and

JSContext instances hosted by the same virtual machine—attempting to pass a value to a different virtual machine raises an Objective-C exception.

你只能传递JSValue实例给在JSValue和JSContext实例的方法,这些实例都被共同的虚拟机器主持,尝试传递一个值给一个虚拟的机器将会唤起一个oc的例外。

6、When you use the methods listed in Creating JavaScript Values and Reading and Converting JavaScript Values, JavaScriptCore automatically converts native values to JavaScript values and vice versa, using the rules summarized below.

当你使用那些转换方法的时候,javaScriptCore 自动的转换这些native值为javaScript值,反之亦然。使用下面这些被总结的规则

vice versa 反之亦然

7、NSDictionary objects or Swift dictionaries and the keys they contain become JavaScript objects with matching named properties and vice versa. Values for keys are recursively copied and converted.

字典对象或者swift字典和他们包含的键变成javaScript 对象,这些对象拥有相同名字的属性和他匹配,反之亦然。键的值会被拷贝或者转换。

8、NSArray objects or Swift arrays become JavaScript arrays and vice versa, with elements recursively copied and converted.

数组对象或者swift 数组通过对元素的拷贝或者转换,能变成javaScript数组,反之亦然。

9、Objective-C blocks (or Swift closures with the@convention(block) attribute) become JavaScriptFunction objects, with parameter and return types converted using the same rules as values. Converting a JavaScript function backed by a native block or method returns that block or method; all other JavaScript functions convert as empty dictionaries.

oc block 或者swift 闭包 会变成javaScript的函数对象,他们的参数和返回值的转换方法跟值的转换一样,转换一个包含本地block或者方法的函数,会返回一个闭包或者方法,所有其他的JavaScript函数转换为空的字典。

10、For all other native object types (and class types or metatypes), JavaScriptCore creates a JavaScript wrapper object with a constructor prototype chain reflecting the native class hierarchy. By default, the JavaScript wrapper for a native object does not make that object’s properties and methods available in JavaScript. To choose properties and methods for export to JavaScript

对于所有其他的类型,JavaScriptCore创建了一个javaScript wrapper 对象,这个对象有一个构造者类型链,这个链条反应了native 类层级,默认情况下,这个对本地对象的javaScript wrapper没有让这个对象的属性和方法在javaScript上可行,必须选择属性和方法导入javaScript里面。

https://developer.apple.com/documentation/javascriptcore/jsmanagedvalue

JSVirtualMachine

1AJSVirtualMachine instance represents a self-contained environment for JavaScript execution. You use this class for two main purposes: to support concurrent JavaScript execution, and to manage memory for objects bridged between JavaScript and Objective-C or Swift

虚拟机器代表一个独立的javaScript 执行环境,你使用这个类两个目的:一是支持并发的java执行环境,二是管理在javaScript和oc或swift之间的桥梁对象。

2、Each JavaScript context (a JSContext object) belongs to a virtual machine. Each virtual machine can encompass multiple contexts, allowing values (JSValueobjects) to be passed between contexts.

每个javaScript context 都属于一个虚拟机器,每个虚拟机器能压缩多个上下文,允许值在context间传递.

3、However, each virtual machine is distinct—you cannot pass a value created in one virtual machine to a context in another virtual machine

然而每个虚拟机器都是独特的,你不能传递这个机器创建的值给另一个机器创建的上下文。

4、The JavaScriptCore API is thread safe—for example, you can create JSValue objects or evaluate scripts from any thread—however, all other threads attempting to use the same virtual machine will wait. To run JavaScript concurrently on multiple threads, use a separate JSVirtualMachine instance for each thread.

javaScriptCore API是线程安全的,例如,你能从任何线程创建jsValue对象或者计算脚本,然而,任何其他尝试使用相同的虚拟机器的线程将要等待,在主线程并发的运行javaScript,每个线程使用一个单独的虚拟机器。

Managing Memory for Exported Objects

5、When you export an Objective-C or Swift object to JavaScript, you must not to store JavaScript values in that object

当你导入一个oc或者swift对象给javaScript的时候,你禁止在那个对象里面存取javaScript值。

6、This action creates a retain cycle—JSValueobjects hold strong references to their enclosing JavaScript contexts, and JSContext

objects hold strong references to the native objects you export to JavaScript

这个行动会创建一个引用环,jsValue对闭合的context有一个强引用,而JSContext 对象会对你引入到javaScript的本地对象持有一个强引用。

7、Instead, use use the JSManagedValueclass to conditionally retain a JavaScript value, and report the native ownership chain for that managed value to the JavaScriptCore virtual machine. 

然后,使用JSManagedValue 类来对java value条件引用,报导管理值得native关系链给虚拟管理器。

Use the addManagedReference(_:withOwner:)and removeManagedReference(_withOwner:)methods to describe your native object graph to JavaScriptCore. After you remove the last managed reference for an object, that object can be safely destroyed by the JavaScript garbage collector.

使用这些方法来描述你native object graph给javaScriptCore.在你移除那个对象的管理引用后,这个对象就会被垃圾机制安全销毁。


bridge学习

1、拦截url方法

WKWebView

(void)webView:(WKWebView *)webView

decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction

decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler


点击首先触发这个方法

UIWebView

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

2、js调用native功能

native注册:

[_webViewBridge registerHandler:@"SDS_WVJS_openDistribOrderListPage" handler:^(id data, WVJBResponseCallback responseCallback) {

        // data的类型与 JS中传的参数有关

        NSDictionary *tempDic = data;

        //在这里执行分享的操作

        NSString *title = [tempDic objectForKey:@"title"];

        NSString *content = [tempDic objectForKey:@"content"];

        NSString *url = [tempDic objectForKey:@"url"];

        

        //将分享的结果返回到JS

        NSString *result = [NSString stringWithFormat:@"分享成功:%@,%@,%@",title,content,url];

        responseCallback(result);

    }];

js调用:

function SDS_WVJS_openDistribOrderListPage() {

                WebViewJavascriptBridge.callHandler('SDS_WVJS_openDistribOrderListPage', {'foo':'bar'},function(response) {

                    alert('扫描结果:' + response);

                    document.getElementById("returnValue").value = response;

                })

            }

3、native 调用js功能

js注册:

setupWebViewJavascriptBridge(function(bridge) {

     bridge.registerHandler('testJSFunction',function(data, responseCallback) {

        alert('JS方法被调用:'+data);

        responseCallback('js执行过了');

     })

    // 注册其他的功能

    //bridge.regsiterHandler.....

})

native 调用:

[_webViewBridge callHandler:@“testJSFunction”];

4、hmtl里在调用native功能之前,要先添加一个js方法,然后主动调用该方法。

function setupWebViewJavascriptBridge(callback) {

    if (window.WebViewJavascriptBridge) {return callback(WebViewJavascriptBridge); }

    if (window.WVJBCallbacks) {returnwindow.WVJBCallbacks.push(callback); }

    window.WVJBCallbacks = [callback];

    var WVJBIframe = document.createElement('iframe');

    WVJBIframe.style.display = 'none';

    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';

    document.documentElement.appendChild(WVJBIframe);

    setTimeout(function() { document.documentElement.removeChild(WVJBIframe) },0)

}

5、处理方法

- (void)WKFlushMessageQueue {

    [_webViewevaluateJavaScript:[_basewebViewJavascriptFetchQueyCommand]completionHandler:^(NSString* result,NSError* error) {

        if (error !=nil) {

            NSLog(@"WebViewJavascriptBridge: WARNING: Error when trying to fetch data from WKWebView: %@", error);

        }

        [_baseflushMessageQueue:result];

    }];

}

6、派发方法

- (void)_queueMessage:(WVJBMessage*)message {

    if (self.startupMessageQueue) {

        [self.startupMessageQueueaddObject:message];

    } else {

        [self_dispatchMessage:message];

    }

}

7、计算方法

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullableid,NSError *_Nullable error))completionHandler

8- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值