Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting background color from UIWebView html?

I've got a smaller UIWebView within a UIView. I want to set the UIView's background color to be the same as the webView's loaded HTML. Is this possible?

I've tried, in webViewDidFinishLoad, to get the color like this:

 NSLog(@"color: %@", [webView stringByEvaluatingJavaScriptFromString: @"document.body.style.background"]);

.. but it doesn't return anything.

like image 284
cannyboy Avatar asked Aug 25 '13 08:08

cannyboy


2 Answers

working code in only three steps ..

1)Copy code and paste it in your project.
2)Connect ___webView outlet to UIWebView in xib file.
3)Run.

- (void)viewDidLoad
{
    [___webView loadHTMLString:[NSString stringWithFormat:@"<html><body id=\"mybody\" style=\"background-color:green;width:100px;height:100px;\"><b>Hello buddy</b></body></html>"] baseURL:nil];
    ___webView.delegate=self;

    [super viewDidLoad];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *javaScript = @"document.body.style.background";
    NSLog(@"color is %@",[webView stringByEvaluatingJavaScriptFromString:javaScript]);
    NSLog(@"did load finish ");
}

//output is -----

2013-09-03 11:56:33.187 ads[3655:11303] color is green
2013-09-03 11:56:33.188 ads[3655:11303] did load finish

like image 121
Prince Kumar Sharma Avatar answered Sep 22 '22 22:09

Prince Kumar Sharma


In HTML resource. I use

body bgcolor="#FF0000"

In that case my code should be.

- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSLog(@"Done loading");
NSLog(@"color1: %@", [webView stringByEvaluatingJavaScriptFromString:     @"document.body.bgColor"]);
}

Output was -

 2013-09-02 16:47:53.986 WebViewTest[14674:707] color1: #FF0000

Now, In HTML resource, I use

body style="background-color:#FF0000"

In that case my code should be.

- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSLog(@"Done loading");
    NSLog(@"color1: %@", [webView stringByEvaluatingJavaScriptFromString: @"document.body.style.backgroundColor"]);

}

Output was -

 2013-09-02 16:55:11.531 WebViewTest[14691:707] color1: rgb(255, 0, 0)

As you can see, depending on how you apply bgcolor to HTML, also changes the way you access it via java script....

Hope this helps!

like image 22
TorukMakto Avatar answered Sep 22 '22 22:09

TorukMakto