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.
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With