在webview中加载本地JavaScript?

我正在使用我自己的广告在swift移动浏览器,我想运行脚本。我已经注入JavaScript本地文件,但它打开其他窗口并重写webview内容。是否有可能在webview页面中运行JavaScript代码? 不在其他窗口中,只在页面内容的页面上。希望你能得到它

使用WKWebView进行javascript方法调用:

第1步。为webkit导入类

Obj-C: #import <WebKit/WebKit.h>
Swift: import WebKit

第2步。创build一个WKWebView实例(不幸的是它只能以编程方式完成)

Obj-C @property (strong, nonatomic) WKWebView *wkWebView;

Swift var wkWebView: WKWebView? = WKWebView() var wkWebView: WKWebView? = WKWebView()

第3步。然后在viewDidLoad

OBJ-C:

  WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; NSString *scriptSourceCode = @"your javascript code here"; WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]; WKUserContentController *controller = [[WKUserContentController alloc] init]; [controller addUserScript:script]; configuration.userContentController = controller; _wkWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration]; [self.view addSubview:_wkWebView]; 

迅速:

  let configuration = WKWebViewConfiguration() let controller = WKUserContentController() let scriptSourceCode = "your javascript code here" let script = WKUserScript(source: scriptSourceCode, injectionTime: WKUserScriptInjectionTime.AtDocumentStart, forMainFrameOnly: true) controller.addUserScript(script) configuration.userContentController = controller self.wkWebView = WKWebView(frame: self.view.frame, configuration: configuration) self.view.addSubview(self.wkWebView!) 

步骤4wkWebView加载一个HTMLstring(或一个loadRequest):

OBJ-C:

 [_wkWebView loadHTMLString:_desiredHTML baseURL:[[NSBundle mainBundle] bundleURL]]; 

迅速:

 self.wkWebView?.loadHTMLString(_desiredHTML, baseURL: NSBundle.mainBundle().bundleURL) 

第5步 。 调用包含在WKWebView中的javascript中存在的方法

OBJ-C:

  NSString *callMethod = [NSString stringWithFormat:@"existingMethodWithParam(%@)", stringParam]; [_wkWebView evaluateJavaScript:callMethod completionHandler:^(id obj, NSError *error) { if (error) { NSLog(@"ERROR evaluating JavaScript - %@", error); } else { NSLog(@"Returned value - %@", obj); //if the javascript method has a return type } }]; 

迅速:

  let callMethod = String(format: "existingMethodWithParam(%@)", stringParam) [self.wkWebView?.evaluateJavaScript(callMethod, completionHandler: { (obj, error) -> Void in println(obj) println(error) })]