加载网页时执行javascript代码
let mWebView = WKWebView.init(frame: self.view.bounds) self.view.addSubview(mWebView) //加载请求 let request = NSURLRequest.init(URL: NSURL.init(string: "http://www.baidu.com/")!) mWebView.loadRequest(request) //编写javascript代码,并在加载网页时执行 let js1 = "var button = document.getElementsByTagName(‘button‘)[0];" let js2 = "button.parentNode.removeChild(button);" let js=js1+js2</span> let script = WKUserScript(source: js, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true) mWebView.configuration.userContentController.addUserScript(script)
我自己写了个简单的html网页,作为测试用,文件名为test
<html> <head> <meta charset="utf-8"> <title>测试网页</title> <style type="text/css"> body button{ color: red; background-color: blue; width: 200px; } .list{ background-color: #ffff00; } </style> </head> <body> <br> <br> <br> <P> </P> <ul > </ul> <br> <button onclick="window.webkit.messageHandlers.YX.postMessage(‘专注探索‘)">按钮1</button> <button>按钮2</button> <button onclick="window.webkit.messageHandlers.{YX}.postMessage(kkkkkkkkkk)">这按钮3</button> </body> </html>
WKWebView获得网页传递的数据,和js进行交互
import UIKit import WebKit class ViewController: UIViewController ,WKScriptMessageHandler,WKUIDelegate,WKNavigationDelegate { override func viewDidLoad() { super.viewDidLoad() //创建一个WKWebView,并添加到控制器的view中 let mWebView = WKWebView.init(frame: self.view.bounds) self.view.addSubview(mWebView) //加载请求 let url1 = NSURL.fileURLWithPath("/Users/yinqixing/Documents/0102--自己编的网页/0102--自己编的网页Tests/test.html") // let url = NSBundle.mainBundle().URLForResource("test", withExtension: "html") let request = NSURLRequest.init(URL: url1) mWebView.loadRequest(request) //编写javascript代码,并在加载网页时执行 let js1 = "var button = document.getElementsByTagName(‘button‘)[1];" let js2 = "button.parentNode.removeChild(button);" let js=js1+js2 let script = WKUserScript(source: js, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true) mWebView.configuration.userContentController.addUserScript(script) mWebView.UIDelegate = self mWebView.navigationDelegate = self //注意 控制器要遵守WKScriptMessageHandler这个协议 //网页代码加入的交互代码: window.webkit.messageHandlers.YX.postMessage() mWebView.configuration.userContentController.addScriptMessageHandler(self, name: "YX") } //实现WKScriptMessageHandler协议中的方法 func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { print(message.body) //打印结果为 专注探索 }
时间: 2024-10-11 00:00:55