我在swift中使用我自己的广告制作移动浏览器,我想运行脚本。我已经注入了javascript本地文件,但它在其他窗口中打开并覆盖webview内容。是否可以在webview中运行javascript代码页?不在其他窗口,只在包含页面内容的页面中。希望你能得到它
答案 0 :(得分:5)
WKWebView
进行javascript方法调用:第1步。导入webkit的类
Obj-C:#import <WebKit/WebKit.h>
斯威夫特:import WebKit
第2步。创建WKWebView
实例(不幸的是,它只能以编程方式完成)
Obj-C @property (strong, nonatomic) WKWebView *wkWebView;
Swift 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!)
第4步在wkWebView
中加载HTML字符串(或loadRequest):
的OBJ-C:
[_wkWebView loadHTMLString:_desiredHTML baseURL:[[NSBundle mainBundle] bundleURL]];
夫特:
self.wkWebView?.loadHTMLString(_desiredHTML, baseURL: NSBundle.mainBundle().bundleURL)
第5步。调用WKWebView
的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)
})]