我的代码非常简单,如下所示:
@interface ViewController ()
{
UIWebView *_webView;
SContext *_jsContext;
}
@end
@implementation ViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_webView = [[UIWebView alloc] initWithFrame:self.view.frame];
[self.view addSubview:_webView];
_webView.delegate = self;
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com"]]];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 100, 50)];
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
[button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
}
- (void)click
{
NSLog(@"documentView.webView.mainFrame.javaScriptContext!");
[_jsContext evaluateScript:@"alert('Hello Word')"];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
_jsContext = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
}
@end
但是,单击该按钮时,不会显示警告窗口。我也尝试评估脚本和#34; console.log('哦,我的上帝')"通过jsContext,但它也不起作用。