开发者

WebView load css on the fly

开发者 https://www.devze.com 2022-12-24 00:03 出处:网络
I have the following code which loads and html file into a webview - (void)awakeFromNib{ NSString *resourcesPath = [[NSBundle mainBundle] resourcePath];

I have the following code which loads and html file into a webview

- (void)awakeFromNib{

    NSString *resourcesPath = [[NSBundle mainBundle] resourcePath];
    NSString开发者_运维百科 *htmlPath = [resourcesPath stringByAppendingString:@"/main.html"];
    [[self mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:htmlPath]]];

}

How would i dynamically load a css file (in the most efficient manner) as it does not suit to have the css file link in the html file


You should access the DOM using the Objective-C DOM API and insert the appropriate <link> or <style> element into the DOM.

DOMDocument* domDocument=[webView mainFrameDocument];
DOMElement* styleElement=[domDocument createElement:@"style"];
[styleElement setAttribute:@"type" value:@"text/css"];
DOMText* cssText=[domDocument createTextNode:@"body{font-weight:bold;}"];
[styleElement appendChild:cssText];
DOMElement* headElement=(DOMElement*)[[domDocument getElementsByTagName:@"head"] item:0];
[headElement appendChild:styleElement];
0

精彩评论

暂无评论...
验证码 换一张
取 消