html文件的代码
<!DOCTYPE html>
<html>
<head>
<title>标题</title>
</head> <body>
<input type="button" class="inputBut" name="test" value="send massage"
onClick="myFunction()">
</body> <script type="text/javascript">
function myFunction()
{
alert("Hello World!");
}
</script>
</html>
iOS 工程的代码
#import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
#import "AppDelegate.h"
#import "RootViewController.h"
@interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor]; self.window.rootViewController = [[RootViewController alloc] init]; [self.window makeKeyAndVisible];
return YES;
} @end
#import <UIKit/UIKit.h> @interface RootViewController : UIViewController @end
#import "RootViewController.h" @interface RootViewController () @property (nonatomic, strong)UIWebView *webView; @end @implementation RootViewController - (void)viewDidLoad {
[super viewDidLoad];
self.webView = [[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.view addSubview:self.webView];
// self.webView.hidden = YES; // 加载本地HTML文件
NSString *path = [[NSBundle mainBundle] pathForResource:@"button" ofType:@"html"];
NSURL *url = [NSURL URLWithString:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request]; // 添加按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(, , , );
btn.backgroundColor = [UIColor redColor];
[btn setTitle:@"触发js按钮" forState:];
[btn addTarget:self action:@selector(callJavaScriptFunction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn]; } - (void)callJavaScriptFunction:(UIButton *)sender
{
NSString *aString = [self.webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];
NSLog(@"=== %@",aString);
} @end