Search code examples
iosuiwebview

How to change src value in UIWebView?


In a UIWebview I want to change

<iframe src=“//player.vimeo.com/video/164231311?autoplay=1” width=“700" height=“394” frameborder=“0" webkitallowfullscreen=“” mozallowfullscreen=“” allowfullscreen=“”></iframe>

to

<iframe src=“//player.vimeo.com/video/164231311" width=“700” height=“394" frameborder=“0” webkitallowfullscreen=“” mozallowfullscreen=“” allowfullscreen=“”></iframe>

since I want the user to be presented with a play button instead of a pause button since autoplay is not allowed on iOS. It'll be more natural for the user to see a play button directly instead of the pause button as in the image below.

How do I do that in a simple way? I’ve tried some stuff like

webView.stringByEvaluatingJavaScript(from:“document.getElementsByTagName(…) 

without success so far.

enter image description here


Solution

  • Here I made rough demo code to solve your issue. Put your logic with that and it will solve your issue. It was tested and had seems working perfectly.

    import UIKit
    
    class ViewController: UIViewController,UIWebViewDelegate {
    
        @IBOutlet weak var webView: UIWebView!
        override func viewDidLoad() {
            super.viewDidLoad()
            webView.delegate = self
            webView.loadRequest(URLRequest(url: URL(string: "file:///Users/user/Downloads/index.html")!))
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        func webViewDidFinishLoad(_ webView: UIWebView) {
            // get your current iframe src value
            let iframeSrcValue:String = webView.stringByEvaluatingJavaScript(from: "document.getElementsByTagName('iframe')[0].src")!
    
            // Here is your current value with AutoPlay
            print(iframeSrcValue)
    
            //Create new URL without Auto Play
            let modifiedSrcValue = "https://www.youtube.com/embed/td8pYyuCIIs"
    
            // Apply it to webview
            let evaluate: String = "document.getElementsByTagName('iframe')[0].src='\(modifiedSrcValue)';"
            webView.stringByEvaluatingJavaScript(from: evaluate)
        }
    
    }