2

I got a UIWebView and I load the content like that

let url = NSURL (string: "http://www.myresponsivesite.fr/section/");
    let requestObj = NSURLRequest(URL: url!);
    webView.loadRequest(requestObj);

It's working perfectly but I would like to put some div and other elements in display none. So my question is : How can I inject some css from my app with swift? Thanks.

matheo972
  • 129
  • 5
  • 13

2 Answers2

2

I finally found another way, I load my html in a variable and, i replace some div with a "display:none" exemple :

 let urlDeBase = "http://mywebsite/section/"    
    if let url = NSURL (string: urlDeBase){
        var error: NSError?
        let myHTML = String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error)

and I replace what i want

 let mystring = myHTML?.stringByReplacingOccurrencesOfString("<h3 class=\"myclass\">Menu</h3>", withString: "<h3 class=\"myclass\" style=\"display:none\">Menu</h3>")
 webvieww.loadHTMLString(mystring, baseURL: nil)
matheo972
  • 129
  • 5
  • 13
1

I found a couple post on it and the Apple docs, here was one solution:

So, I think I found at least one way to accomplish appending styles to the webpage being loaded using Swift:

var loadStyles = "var script = 
  document.createElement('link');
  script.type = 'text/css';
  script.rel = 'stylesheet';
  script.href = 'http://fake-url/styles.css';
  document.getElementsByTagName('body')[0].appendChild(script);"

website.stringByEvaluatingJavaScriptFromString(loadStyles)

Here is the other post: Swift stringByEvaluatingJavaScriptFromString

Then the Apple docs.

Community
  • 1
  • 1
Caleb Kleveter
  • 11,170
  • 8
  • 62
  • 92
  • If I understood, the var is going to create a css file, so if i add one more line in the var just like : "script.text = #myId { display : none; }" is it good ? – matheo972 Sep 03 '15 at 13:46
  • I can't really say, I don't have any experience with it. You will have to mess around with it. I tried to find information on how it works exactly but I couldn't find any. – Caleb Kleveter Sep 03 '15 at 16:23