85056

How to load CSS file by using URL in WKWebView

<h3>Question</h3>

I want to inject CSS by using URL link ,

Working

Working below code, If I store CSS file in Bundle path of project,

lazy var webView: WKWebView = { guard let path = Bundle.main.path(forResource: "style", ofType: "css") else { return WKWebView() } let cssString = try! String(contentsOfFile: path).components(separatedBy: .newlines).joined() let source = """ var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style); """ let preferences = WKPreferences() preferences.setValue(true, forKey:"developerExtrasEnabled") let userScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true) let userContentController = WKUserContentController() userContentController.addUserScript(userScript) let configuration = WKWebViewConfiguration() configuration.userContentController = userContentController configuration.preferences = preferences let webView = WKWebView(frame: .zero, configuration: configuration) webView.navigationDelegate = self webView.scrollView.isScrollEnabled = false webView.scrollView.bounces = false return webView }()

Expectation

I have CSS file which is store in our server having some path link let say ,

https://xyz/styles/style.css

So I want to apply style.css file by using URL link ,

Please help me to apply CSS file by using URL only , I don't want to store it in bundle , bundle CSS file is already working for me , our CSS style will change dynamically so I want apply URL link CSS file.


<h3>Answer1:</h3>

You can download the remote css file just like any other file type.

Here's a simple example (note: <em>just an example!!!</em> - not intended to be production code!):

func gotTheCSS(_ css: String) -> Void { print(css) // here is where you would inject it, just like you did when // loading it from the bundle } override func viewDidLoad() { super.viewDidLoad() DispatchQueue.global().async { if let url = URL(string: "http://yoursite.com/css/style.css") { do { let cssString = try String(contentsOf: url, encoding: String.Encoding.utf8) self.gotTheCSS(cssString) } catch { print(error) } } } }
<h3>Answer2:</h3>

Thanks folks for help/suggestion/answers on my question.

I have find solution to apply CSS file to webview by using URL of CSS file .

Use your backend server link for CSS file like ,

let cssURL "https://xyz/styles/style.css" // Use your server css file url link

Then issue with JavaScript injection so , I have change JavaScript injection code style to link like below code, All code I have write in <em>"override func viewDidAppear(_ animated: Bool)"</em> method , just copy paste code,It will work to you as well .

let source = """ var link = document.createElement('link'); link.href = '\(url)'; link.rel= 'stylesheet' document.head.appendChild(link); """ let userScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true) let userContentController = WKUserContentController() userContentController.addUserScript(userScript) let configuration = WKWebViewConfiguration() configuration.userContentController = userContentController self.webView = WKWebView(frame: self.documentDiscriptionView.bounds, configuration: configuration) self.webView.navigationDelegate = self self.webView.scrollView.isScrollEnabled = false self.webView.scrollView.bounces = false self.webView.isOpaque = false self.webView.backgroundColor = UIColor.clear self.webView.scrollView.backgroundColor = UIColor.clear self.self.webViewContainerView.addSubview( self.webView) ///// Set Constraint self.webView.translatesAutoresizingMaskIntoConstraints = false self.webView.leadingAnchor.constraint(equalTo: self.webViewContainerView.leadingAnchor, constant: 0).isActive = true self.webView.trailingAnchor.constraint(equalTo: self.webViewContainerView.trailingAnchor, constant: 0).isActive = true self.webView.topAnchor.constraint(equalTo: self.webViewContainerView.topAnchor, constant: 0).isActive = true self.webView.bottomAnchor.constraint(equalTo: self.webViewContainerView.bottomAnchor, constant: 0).isActive = true

My issue is resolved now , Hope so this solution will help to someone to apply css by using link, Please let me know if any one wants any kind of help to apply CSS to webView, I will happy to help .

来源:https://stackoverflow.com/questions/61893390/how-to-load-css-file-by-using-url-in-wkwebview

Recommend

  • How to load CSS file by using URL in WKWebView
  • How to set size of MARGINS in GridLayout
  • Have I implemented EpicPandaForce's RealmManager correctly?
  • Out of memory error on byte allocation?
  • Multiple (single) dates selector using jquery ui datepicker?
  • About thread safety in malloc and free [duplicate]
  • how to plot the data for linear model with 3 variables in matlab?
  • Implementing an interactive R console in c# / rdotnet? [closed]
  • UItextField data disappears when I scroll through the TableView — Swift
  • Can testing with real adMob ads after the app's development results in adMob's policy viol
  • Convert a Base64 LDIF file to plaintext (for import)
  • getting user info google plus api
  • C# library for .NET Core and .NET Framework
  • Can't subscribe to Push notification
  • Oracle JDBC UCP and Java
  • Should I use CloudFront together as TemporaryUrl for sensitive files in s3
  • Unknown number of sublists with AngularJS
  • How to center text in C console? [duplicate]
  • Uploading an Image through Admin in Django
  • Trying to display location data from Firebase to MapKit
  • Returned value cannot be converted to WebElement
  • How to find DWARF_DSYM_FOLDER_PATH and DWARF_DSYM_FILE_NAME in xcode 9.3
  • my javascript in external html is not loading
  • Class return value to another function in same class
  • I keep getting this error, XML Parsing error: syntax error but still the website runs fine
  • Chaining Requests using BlueBird/ Request-Promise
  • Using gson, how to exclude a numeric type (double, integer) with default value from serialization?
  • How to load PDFs from Documents Directory?
  • Deleting/“Rebasing” rails migrations
  • if there is no internet connection, hide iframe
  • Erlang needs to connect to https server?
  • Objects Sorting With date ,Time Problem in Array(Iphone Development)
  • get value using jquery
  • Http Requests not getting routed to Https NodeJs
  • .Net how to set IsReadOnly for a property for a usercontrol
  • Random number of FORM fields being prepared for database
  • Creating and managing two independent random number sequences
  • Example of using Service Exists MSBuild task in Microsoft.Sdc.Tasks?
  • using maven pom while creating jar:test-jar some times it says JAR will be empty - no content was ma
  • Running R's aov() mixed effects model from Python using rpy2