JSContext实现js注入

本文记录了iOS端实现js注入的基本方法。

webview内进行跳转后之前注入的js失效的问题

可以在下面函数中重新进行js注入:

1
2
3
4
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[webView setupJSContext];
}

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@protocol MyPointExports <JSExport>
@property double x;
@property double y;
- (NSString *)description;
- (instancetype)initWithX:(double)x y:(double)y;
+ (MyPoint *)makePointWithX:(double)x y:(double)y;
@end

@interface MyPoint : NSObject <MyPointExports>
- (void)myPrivateMethod; // Not in the MyPointExports protocol, so not visible to JavaScript code.
@end

@implementation MyPoint
// ...
@end
1
2
3
4
5
6
- (void)setupJSContext
{
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
MyPoint *mobile=[[MyPoint alloc] init];
context[@"mobile"]=mobile;
}