JavaScript注入WKWebView
2019-04-19 本文已影响0人
严青_
为了便于js的管理,每个需要注入的js我都单独创建了一个js文件,如图
![](https://img.haomeiwen.com/i10075901/94edb4a7ece6761d.png)
js内容是用来禁止web右键功能,主要是防止打开web调试控制器
!不需要添加script标签
//禁用右键(防止右键查看源代码)
window.oncontextmenu=function(){return false;}
//禁止任何键盘敲击事件(防止F12和shift+ctrl+i调起开发者工具)
window.onkeydown = window.onkeyup = window.onkeypress = function () {
window.event.returnValue = false;
return false;
}
//如果用户在工具栏调起开发者工具,那么判断浏览器的可视高度和可视宽度是否有改变,如有改变则关闭本页面
var h = window.innerHeight,w=window.innerWidth;
window.onresize = function () {
if (h!= window.innerHeight||w!=window.innerWidth){
window.close();
window.location = "about:blank";
}
}
只需要在 WKWebViewConfiguration中进行设置即可
let webConfig = WKWebViewConfiguration()
webConfig.userContentController = WKUserContentController()
webConfig.preferences = preferences
if let path = Bundle.main.path(forResource: "BanWebInteraction", ofType: "js") {
do{
let data = try Data.init(contentsOf: URL.init(fileURLWithPath: path), options: [.mappedRead])
let source = String.init(data: data, encoding: String.Encoding.utf8) ?? ""
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
webConfig.userContentController.addUserScript(userScript)
}catch{}
}