简体   繁体   中英

Insert Viewport meta in HTML file using Javascript

in my example I'd like to inject Javascript into the content of UiWebView RSS_Dettaglio_Webv . Why am I not able to insert viewport meta?

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:storyLink]];
[RSS_Dettaglio_Webv loadRequest:request];
[RSS_Dettaglio_Webv setBackgroundColor:[UIColor whiteColor]];

NSString *javaScript = @"var viewPortTag=document.createElement('meta');\
viewPortTag.id=""viewport"";\
viewPortTag.name = ""viewport"";\
viewPortTag.content = ""width=320"";\
document.getElementsByTagName('head')[0].appendChild(viewPortTag);";

[RSS_Dettaglio_Webv stringByEvaluatingJavaScriptFromString:javaScript];

meta tags are parsed when the document is loaded, but otherwise they'll be ignored. Note that I use pure js to detect viewport size, and adjust the html page to that.

UPDATE

If you must use the meta tag, you can load the HTML as a string rather than a file, modifying the string before loading it... something like this (untested code) - where you put "width:device-width" into the meta tag, then search and replace it:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"htm"];  
if (filePath) {  
    NSString *firstHTML = [NSString stringWithContentsOfFile:filePath];  
    if (firstHTML) {
        NSString *html;
        html = [firstHTML stringByReplacingOccurancesOfString:@"device-width" withString:@"320"];  
        [self.webView loadHTMLString:html baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
    }  
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM