How to detect a movie being played in a WKWebView?

前端 未结 2 679
轮回少年
轮回少年 2020-12-23 12:44

I\'d like to know wether it\'s possible to detect a movie being played in the WKWebView?

Additionally I\'d like to know the exact URL of the opened stream?

2条回答
  •  轮回少年
    2020-12-23 13:18

    I tried to add (inject) some user script to the WKWebView, this way is a little bit safer than method swizzling:

    Here is related code:

    let contentController = WKUserContentController()
    
    if let jsSource = NSBundle.mainBundle().URLForResource("video_play_messenger", withExtension: "js"),
        let jsSourceString = try? String(contentsOfURL: jsSource) {
        let userScript = WKUserScript(source: jsSourceString, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)
    
        contentController.addUserScript(userScript)
        contentController.addScriptMessageHandler(self, name: "callbackHandler")
    }
    
    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.userContentController = contentController
    
    webView = WKWebView(frame: CGRect.zero, configuration: webConfiguration)
    let request = NSURLRequest(URL: NSURL(string: "URL_FOR_VIDEO")!)
    webView.loadRequest(request)
    

    For the controller of WKWebView, conform to WKScriptMessageHandler and implement this method:

    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
        if message.name == "callbackHandler" {
            if let messageString = message.body as? String where messageString == "VideoIsPlaying" {
                // Vide is being played
            }
        }
    }
    

    Add video_play_messenger.js to your project:

    function videoTags() {
        return document.getElementsByTagName("video");
    }
    
    function setupVideoPlayingHandler() {
        try {
            var videos = videoTags()
            for (var i = 0; i < videos.length; i++) {
                videos.item(i).onplaying = function() {
                    webkit.messageHandlers.callbackHandler.postMessage("VideoIsPlaying");
                }
            }
        } catch (error) {
            console.log(error);
        }
    }
    
    function setupVidePlayingListener() {
        // If we have video tags, setup onplaying handler
        if (videoTags().length > 0) {
            setupVideoPlayingHandler();
            return
        }
    
        // Otherwise, wait for 100ms and check again.
        setTimeout(setupVidePlayingListener, 100);
    }
    
    setupVidePlayingListener();
    

    Reference: http://www.kinderas.com/technology/2014/6/15/wkwebview-and-javascript-in-ios-8-using-swift

提交回复
热议问题