简体   繁体   中英

WKWebView stop audio when backgrounding app

I have a WKWebView which is playing HTML5 video. When I click the home button and the app enters the background I can still hear the audio playing. How can I pause the HTML 5 video to stop the background audio from playing. I tried just loading a blank page when the app enters background which works,

let url = URL(string: "about:blank")
let request = URLRequest(url:url!)
self.webView.load(request) 

but I want to be able to start the video at the same point when the user returns from the background so it is not a viable solution since it just loads the blank page when I open the app back up.

I was able to achive this by injecting JavaScript when the app entered the background which would pause any video elements that are playing.

NotificationCenter.default.addObserver(self, selector: #selector(enteredBackground(notification:)), name: UIApplication.didEnterBackgroundNotification, object: nil)

@objc func enteredBackground(notification: Notification) {
    let script = "var vids = document.getElementsByTagName('video'); for( var i = 0; i < vids.length; i++ ){vids.item(i).pause()}"
    self.webView.evaluateJavaScript(script, completionHandler:nil)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM