【发布时间】:2017-04-21 16:17:08
【问题描述】:
我正在使用WKWebView 打开pages in Youtube。问题是在打开时他们开始播放视频并全屏显示,这是不想要的行为。视频没有嵌入,它是带有描述、cmets 等的整个页面。
有没有办法阻止他们玩?
【问题讨论】:
-
我也有同样的问题。
我正在使用WKWebView 打开pages in Youtube。问题是在打开时他们开始播放视频并全屏显示,这是不想要的行为。视频没有嵌入,它是带有描述、cmets 等的整个页面。
有没有办法阻止他们玩?
【问题讨论】:
它有效。 请阅读 cmets。
import UIKit
import WebKit
import RxSwift
class WebViewController: UIViewController {
let webview: WKWebView
init() {
// ? add config
let config = WKWebViewConfiguration()
config.allowsInlineMediaPlayback = true
if #available(iOS 10.0, *) {
config.mediaTypesRequiringUserActionForPlayback = .video
}
self.webview = WKWebView(frame: .zero, configuration: config)
super.init(nibName: nil, bundle: nil)
webview.frame = view.bounds
subscribeURL()
}
private func subscribeURL() {
self.webview.rx.url
.shareReplay(1)
.subscribe(onNext: { [weak self] url in
guard let url = url else { return }
// ? Navigation Delegate can not detect transition because YouTube is Single Page Application.
startInlinePlayApplyInterval()
})
.addDisposableTo(disposeBag)
}
private func startInlinePlayApplyInterval() {
// ? There is time rag to come out new video element so start repeat interval.
//Useful Timer extension: http://stackoverflow.com/a/39600244/3276863
let loop = Timer.schedule(repeatInterval: 0.2) { [weak self] timer in
self?.applyInlinePlay { success in
if success {
timer?.invalidate()
}
}
}
Timer.schedule(delay: 2) { _ in
loop?.invalidate()
}
}
private func applyInlinePlay(completion: @escaping (Bool)->Void) {
// ? add attributes 'webkit-playsinline','playsinline','controls' to video element
let script = "(function(){var applied=document.querySelector('video').attributes.playsinline!=undefined;if(applied){return false}var videos=document.querySelectorAll('video');var attrList=['webkit-playsinline','playsinline','controls'];for(video of videos){for(attr of attrList){video.setAttribute(attr,'');}}return true})();"
webview.evaluateJavaScript(script) { res, err in
let isSuccessToApply: Bool = (res as? Bool) ?? false
completion(isSuccessToApply)
}
}
}
【讨论】: