WKUserScript无法正常工作 [英] WKUserScript not working
问题描述
我想使用 WKWebview
API注入脚本。由于某种原因它不起作用,我无法弄明白。我已经尝试在 Safari
开发人员控制台中进行调试,但我找不到 JavaScript
代码。
I want to inject a script using WKWebview
API. For some reason it isn't working and I can't figure it out. I've tried debugging in Safari
developer console and I can't find the JavaScript
code in there either.
实施代码如下:
NSString *js = @"document.body.style.background = \"#FF0000\";";
NSString *myScriptSource = @"alert('Hello, World!')";
WKUserScript *s = [[WKUserScript alloc] initWithSource:myScriptSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
WKUserContentController *c = [[WKUserContentController alloc] init];
[c addUserScript:s];
WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc] init];
conf.userContentController = c;
WKWebView *webview = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:conf];
[self.view addSubview:webview];
webview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// Do any additional setup after loading the view, typically from a nib.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
[webview loadRequest:request];
});
推荐答案
alert
默认情况下未在 WKWebView
中实现,因此即使您的用户脚本运行,它也不会明显地执行任何操作。你需要实现 runJavaScriptAlertPanelWithMessage
:
alert
isn't implemented in WKWebView
by default, so even if your user script runs it won't visibly do anything. You need to implement runJavaScriptAlertPanelWithMessage
:
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (() -> Void)) {
let alert = UIAlertController.create(title: frame.request.url?.host, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
completionHandler()
}))
present(alert, animated: true, completion: nil)
}
我不知道认为注入的JavaScript实际上出现在DOM的任何地方,它是 WKWebView
内部的属性。
I don't think the injected JavaScript actually appears in the DOM anywhere, it's a property internal to the WKWebView
.
这篇关于WKUserScript无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!