开发者

Load UIWebView with a CSS local file

开发者 https://www.devze.com 2023-03-23 15:41 出处:网络
I\'m looking for a way to load my UIWebView with a local CSS file that should affect on the UIWebView\'s loadRequest.

I'm looking for a way to load my UIWebView with a local CSS file that should affect on the UIWebView's loadRequest.

For the clearness: I have an UIWebView that I loadRequest it with a website url. I also have a local CSS file that shoul开发者_高级运维d affect this loadRequest url.

I want to load this CSS file onto the UIWebView.

Thanks,


This stackoverflow question appears to have one or two answers that may help you.

You need to load the local CSS (using a method not unlike @Shrey uses, but looking for your CSS file), and somehow inject it into the page, and the only way appears to be to use:

[webview stringByEvaluatingJavaScriptFromString:someJavascriptToInjectCSS];

and some clever Javascript to modify the page to add the CSS in.

Hope this helps point you in the right direction. I have used this method to inject stuff into pages, so it does work, but I don't know Javascript well enough to write the code to inject your CSS into the page.


This is the Swift version.

Load the css file on the webViewDidFinishLoad delegate method and use stringByEvaluatingJavaScriptFromString. Credits here

 func loadWebViewStyles() {
        guard let cssPath = NSBundle.mainBundle().pathForResource("theme", ofType: "css") else {
            return
        }

        let loadStyles = "var script = document.createElement('link');  script.type = 'text/css'; script.rel = 'stylesheet'; script.href = '\(cssPath)'; document.getElementsByTagName('body')[0].appendChild(script);"

        webView.stringByEvaluatingJavaScriptFromString(loadStyles)
    }


try this:

[WebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];

0

精彩评论

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