iOS WKWebView 退出后停止播放音频/视频
带有<video>或者<audio>标签的H5网页在播放音频视频时,退出webview后不会自动停止播放,手动处理一下。
1.注入使网页停止音频、视频播放的JS代码(Swift 4):
1 let pauseJSString:String = 2 """ 3 var videos = document.getElementsByTagName("video"); 4 function pauseVideo(){ 5 var len = videos.length 6 for(var i=0;i<len;i++){ 7 videos[i].pause(); 8 } 9 } 10 var audios = document.getElementsByTagName("audio"); 11 function pauseAudio(){ 12 var len = audios.length 13 for(var i=0;i<len;i++){ 14 audios[i].pause(); 15 } 16 } 17 """ 18 let pauseJS:WKUserScript = WKUserScript.init(source: pauseJSString, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true) 19 20 let userContentCtrl:WKUserContentController = WKUserContentController.init() 21 userContentCtrl.addUserScript(pauseJS) 22 conf.userContentController = userContentCtrl 23 24 webView = WKWebView.init(frame: CGRect.zero, configuration: conf)
2.退出前,调用暂停播放的JS函数(Swift 4):
override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) pausePlay() }
/// 暂停播放网页内的音频、视频 func pausePlay(){ mWebView.evaluateJavaScript("pauseVideo()") { (data, error) in } mWebView.evaluateJavaScript("pauseAudio()") { (data, error) in } }
Ficow原创,转载请注明出处:http://www.cnblogs.com/ficow/p/7637922.html
Stay hungry,stay foolish.