Javascript将CSS注入Swift WebView

时间:2015-04-05 23:51:28

标签: javascript css swift

我试图在xCode上加载页面,然后用另一个文件覆盖它的样式。我在Chrome中手动测试了这一点,页面的2个部分应该变为鲜红色,但它们不在我的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)
}

非常感谢你!

1 个答案:

答案 0 :(得分:0)

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

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

然而,似乎需要一些额外的工作才能让它与任何iOS应用程序一起工作(参见Get Oriented:基于Webkit的应用程序)