IOS JavaScript 桥接

我正在开发一个应用程序,我将在 UIWebView 和本地 iOS 框架中同时使用 HTML5。我知道我可以实现 JavaScript 和 Objective-C 之间的通信。是否有任何库可以简化此通信的实现?我知道有几个库可以用 HTML5和 JavaScript (例如 AppMobi,PhoneGap)创建本地 iOS 应用程序,但我不确定是否有一个库可以帮助创建使用大量 JavaScript 的本地 iOS 应用程序。我需要:

  1. 从 Objective-C 执行 JS 方法
  2. 从 JS 执行 Objective-C 方法
  3. 从 Objective-C 侦听本机 JS 事件(例如 DOM 就绪事件)
113361 次浏览

Your best bet is Appcelerators Titanium offering. They already have built a Obj-C javascript bridge using the V8 engine JavascriptCore engine used by webkit. It's also open source, so you'll be able to download it and tinker with the Obj-C as you like.

There are a few libraries, but I didn't used any of these in big projects, so you might want to try them out:

However, I think it's something simple enough that you might give it a try yourself. I personally did exactly this when I needed to do that. You might also create a simple library that suits your needs.

1. Execute JS methods from Objective-C

This is really just one line of code.

NSString *returnvalue = [webView stringByEvaluatingJavaScriptFromString:@"your javascript code string here"];

More details on the official UIWebView Documentation.

2. Execute Objective-C methods from JS

This is unfortunately slightly more complex, because there isn't the same windowScriptObject property (and class) that exists on Mac OSX allowing complete communication between the two.

However, you can easily call from javascript custom-made URLs, like:

window.location = yourscheme://callfunction/parameter1/parameter2?parameter3=value

And intercept it from Objective-C with this:

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *URL = [request URL];
if ([[URL scheme] isEqualToString:@"yourscheme"]) {
// parse the rest of the URL object and execute functions
}
}

This is not as clean as it should be (or by using windowScriptObject) but it works.

3. Listen to native JS events from Objective-C (for example DOM ready event)

From the above explanation, you see that if you want to do that, you have to create some JavaScript code, attach it to the event you want to monitor and call the correct window.location call to be then intercepted.

Again, not clean as it should be, but it works.

Have a look at the KirinJS project: Kirin JS which allows to use Javascript for the application logic and native UI adequate to the platform it runs on.

The suggested method of calling objective c from JS in the accepted answer isn't recommended. One example of problems: if you make two immediate consecutive calls one is ignored (you can't change location too quickly).

I recommend the following alternative approach:

function execute(url)
{
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", url);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}

You call the execute function repeatedly and since each call executes in its own iframe, they should not be ignored when called quickly.

Credits to this guy.

I created a library like WebViewJavascriptBridge, but it's more JQuery-like, has easier to setup and is easier to use. Doesn't rely on jQuery (though to its credit, had I known WebViewJavascriptBridge existed before writing this I may just have held back slightly before diving in). Let me know what you think! jockeyjs

Update: This has changed in iOS 8. My answer applies to previous versions.

An alternative, that may get you rejected from the app store, is to use WebScriptObject.

These APIs are public on OSX but are not on iOS.

You need to define interfaces to the internal classes.

@interface WebScriptObject: NSObject
@end


@interface WebView
- (WebScriptObject *)windowScriptObject;
@end


@interface UIWebDocumentView: UIView
- (WebView *)webView;
@end

You need to define your object that's going to serve as your WebScriptObject

@interface WebScriptBridge: NSObject
- (void)someEvent: (uint64_t)foo :(NSString *)bar;
- (void)testfoo;
+ (BOOL)isKeyExcludedFromWebScript:(const char *)name;
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector;
+ (WebScriptBridge*)getWebScriptBridge;
@end


static WebScriptBridge *gWebScriptBridge = nil;


@implementation WebScriptBridge
- (void)someEvent: (uint64_t)foo :(NSString *)bar
{
NSLog(bar);
}


-(void)testfoo {
NSLog(@"testfoo!");
}


+ (BOOL)isKeyExcludedFromWebScript:(const char *)name;
{
return NO;
}


+ (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector;
{
return NO;
}


+ (NSString *)webScriptNameForSelector:(SEL)sel
{
// Naming rules can be found at: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/WebKit/Protocols/WebScripting_Protocol/Reference/Reference.html
if (sel == @selector(testfoo)) return @"testfoo";
if (sel == @selector(someEvent::)) return @"someEvent";


return nil;
}
+ (WebScriptBridge*)getWebScriptBridge {
if (gWebScriptBridge == nil)
gWebScriptBridge = [WebScriptBridge new];


return gWebScriptBridge;
}
@end

Now set that an instance to your UIWebView

if ([uiWebView.subviews count] > 0) {
UIView *scrollView = uiWebView.subviews[0];


for (UIView *childView in scrollView.subviews) {
if ([childView isKindOfClass:[UIWebDocumentView class]]) {
UIWebDocumentView *documentView = (UIWebDocumentView *)childView;
WebScriptObject *wso = documentView.webView.windowScriptObject;


[wso setValue:[WebScriptBridge getWebScriptBridge] forKey:@"yourBridge"];
}
}
}

Now inside of your javascript you can call:

yourBridge.someEvent(100, "hello");
yourBridge.testfoo();

In iOS8 you can look at WKWebView instead of UIWebView. This has the following class: WKScriptMessageHandler: Provides a method for receiving messages from JavaScript running in a webpage.

If you are using WKWebView on iOS 8, take a look the XWebView which can automatically expose the native interface to javascript.