Javascript inject CSS into Swift WebView

Javascript inject CSS into Swift WebView

本文关键字:Swift WebView into CSS inject Javascript      更新时间:2023-09-26

我试图在xCode上加载一个页面,然后用另一个文件覆盖它的样式。我已经在Chrome中手动测试过了,页面的两个部分应该变成亮红色,但在我的XCode项目中没有。有什么想法吗?

class ViewController: UIViewController {
var urlPath = "http://grappul.com"
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    loadAddress()
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func loadAddress(){
    let requestURL = NSURL(string:urlPath)
    let request = NSURLRequest(URL: requestURL!)
    webView.loadRequest(request)
    println("got the page!")
    webViewDidFinishLoad(webView)
}
func webViewDidFinishLoad(website: UIWebView){
    var jsscript = "var script = document.createElement('link');
    script.type = 'text/css'; 
    script.rel = 'stylesheet'; 
    script.href = 'http://www.grappul.com/snapkin/restyle.css';
    document.getElementByTagName('head')[0].appendChild(script);"
    println("got the css!")
    website.stringByEvaluatingJavaScriptFromString(jsscript)
}

谢谢大家!

UIWebView似乎没有一个大的JavaScript接口来查找错误报告,但您应该看看Safari Web检查器及其监控任何UIWebView应用程序的能力:

https://developer.apple.com/library/prerelease/ios/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Introduction/Introduction.html

然而,要使其与任何iOS应用程序协同工作,似乎还需要一些额外的工作(请参阅面向对象:基于Webkit的应用程序)