Blocked a frame with origin - ios

I am trying to load javascript to a webview to change color of frame. I am getting "Blocked a frame with origin" error while javascript is being applied.
URL :
https://checkout-testing.herokuapp.com/v3/hosted/pay/7f4d4fd48adde85420e3
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let changeHtmlbuttonScript = """
document.getElementById(checkout).style.backgroundColor = "#0331FC"
"""
webView.evaluateJavaScript(changeHtmlbuttonScript) { (success, error) in
print("Error: \(error)")
}
}
I have tried setting "Arbitrary loads" property to false but no success. Does anyone know how to solve this.

Related

why I can’t open a App Store link inside a web view?

I'm getting always this error :
WebPageProxy::didFailProvisionalLoadForFrame: frameID=3, domain=WebKitErrorDomain, code=102
Normal links are working but the AppStore one is not working
what I want is the Link to open the AppStore I can't do it locally because the web is loaded from a Qualtrics web.
I try it adding the navigationAction function but that doesn't work, what I'm guessing is that maybe the request is taking some time and i need a way of load that data on an async way but to be honest i really dont know
import SwiftUI
import WebKit
struct WebView: UIViewRepresentable {
let html = """
Appstore link dont open</span></span><br />
Normal link </span></span><br />
"""
var loadStatusChanged: ((Bool, Error?) -> Void)? = nil
func makeCoordinator() -> WebView.Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> WKWebView {
let view = WKWebView()
view.navigationDelegate = context.coordinator
view.loadHTMLString(html, baseURL: nil)
return view
}
func updateUIView(_ uiView: WKWebView, context: Context) {
}
class Coordinator: NSObject, WKNavigationDelegate {
let parent: WebView
init(_ parent: WebView) {
self.parent = parent
}
}
}
struct ContentView: View {
var body: some View {
WebView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Some links on tapping them might activate actions / redirect with url schemes that are non HTTPs like
_blank to open a new tab
mailto to launch the mail application
some other deep link techniques familiar to device OSs
I believe the app store link uses a combination of the above and WKWebView cannot handle non HTTPs schemes.
What you can do is to listen to URLs that fail using WKNavigationDelegate and handle them accordingly
I am not using SwiftUI but I think you can get the picture.
Set up using the same HTML as you with both the links
class ViewController: UIViewController, WKNavigationDelegate
{
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
let html = """
Appstore link dont open</span></span><br />
Normal link </span></span><br />
"""
let webview = WKWebView()
webview.frame = view.bounds
webview.navigationDelegate = self
view.addSubview(webview)
webview.loadHTMLString(html, baseURL: nil)
}
}
Then I implement these WKNavigationDelegate functions
decidePolicyFor navigationAction (documentation link) to allow even urls that do not follow the HTTPs scheme to be allowed to be processed
this navigation fail delegate function webView didFailProvisionalNavigation and check if iOS can handle the open in a new tab, mail, deep link etc so in your case it would open the app store
You could also implement the same logic as point 2 in this
WKNavigationDelegate function just in case
// MARK: WKNavigationDelegates
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: #escaping (WKNavigationActionPolicy) -> Void)
{
decisionHandler(.allow)
}
func webView(_ webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: Error)
{
manageFailedNavigation(webView,
didFail: navigation,
withError: error)
}
func webView(_ webView: WKWebView,
didFail navigation: WKNavigation!,
withError error: Error)
{
manageFailedNavigation(webView,
didFail: navigation,
withError: error)
}
private func manageFailedNavigation(_ webView: WKWebView,
didFail navigation: WKNavigation!,
withError error: Error)
{
// Check if this failed because of mailto, _blank, deep links etc
// I have commented out how to check for a specific case like open in a new tab,
// you can try to handle each case as you wish
if error.localizedDescription
== "Redirection to URL with a scheme that is not HTTP(S)"
//let url = webView.url, url.description.lowercased().range(of: "blank") != nil
{
// Convert error to NSError so we can access the url
let nsError = error as NSError
// Get the url from the error
// This key could change in future iOS releases
if let failedURL = nsError.userInfo["NSErrorFailingURLKey"] as? URL
{
// Check if the action can be handled by iOS
if UIApplication.shared.canOpenURL(failedURL)
{
// Request iOS to open handle the link
UIApplication.shared.open(failedURL, options: [:],
completionHandler: nil)
}
}
}
}
Give this a go and check if this fixes your issue. On my side, both links seem to work fine:

WKWebview showing blank page when trying to load local web. How to print errors in console?

I'm trying to load a local web, but is not working, only a white screen is being displayed.
let zipName = webSection?.zipResource?.zipName?.lowercased() {
let zipPath = ProjectPath.path.appending(zipName.deletingPathExtension).appending(pathComponent: "index.html")
let url = URL(fileURLWithPath: zipPath)
//webView.loadFileURL(url, allowingReadAccessTo: url) //suppossedly new method for loading local websites, but it haves same behaviour, blank screen
webView.load(URLRequest(url: url))
In Android, I can see in logcat which errors is generating the webview when no content is being displayed, but here in Xcode I can't see nothing in the console. How can i see which errors is giving the WKWebView?
Implement webView navigation delegate in viewDidLoad
self.webView.navigationDelegate = self
extension ViewController : WKNavigationDelegate {
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print(error.localizedDescription)
}
}

evaluateJavascript is not executing function

How do i execute javascript function at runtime, the function to load the chat window does not get executed
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let javascript =
"const params = {typeId: ‘someid’, callback: getContextCallback} loadChatWindow(params)"
evaluateJavascript(javascript, completion:{ _ in })
}
try catching your error in evaluateJavascript completionHandler to see if your javascript string is correct or not (you need semicolon to separate the js statements as mentioned in the comment). also, evaluateJavascript is webView's method so it should be called like this:
webView.evaluateJavaScript(javascript) { (result, error) in
print(error as? String)}

Can WKWebView instance show webpage while it is loading?

I'm using WKWebView to browse the specific website.
WKWebView instance loads initial page of the website by URL with method load(_ request: URLRequest) -> WKNavigation? Until load request isn't completed I see white screen. Can WKWebView show already loaded parts of the webpage while the rest of the webpage is loading?
Can UIWebView do this trick?
if white screen is your issue, i recommend you to display an custom progress indicator over the webView or some Animation view over your webView.
Once the loading is completed hide the progress indicator.
Start your Animation at:
optional func webView(_ webView: WKWebView,
didStartProvisionalNavigation navigation: WKNavigation!)
{
//Start Progress indicator animation
}
End/Hide your Animation/Progress View at:
optional func webView(_ webView: WKWebView,
didFinish navigation: WKNavigation!)
{
//Stop Progress indicator animation
}
In my case progressive loading started to work when i have added delegate WKWebViewNavigationDelegate to WKWebview and function
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!)
If this func was not added, Web page did not rendered before all content was downloaded in all cases

how to Add timeout for WKWebview

How to write a timeout handler for WKWebView, when default delegates are not getting called for didFailNavigation.
WKWebView delegate are set & DidFinishNavigation or didFailProvisionalNavigation is getting called.
Use the error.code value of the error that didFailProvisionalNavigation creates and add your 'handler' code there:
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
if error.code == -1001 { // TIMED OUT:
// CODE to handle TIMEOUT
} else if error.code == -1003 { // SERVER CANNOT BE FOUND
// CODE to handle SERVER not found
} else if error.code == -1100 { // URL NOT FOUND ON SERVER
// CODE to handle URL not found
}
}
Use this delegate method
webView:didFailProvisionalNavigation:withError:
Document
Invoked when an error occurs while starting to load data for the main frame.
And check the error code
NSURLErrorTimedOut = -1001
All the error code list
One possible solution is to add custom timer, which starts as you call loadHTML, loadRequest methods and times out on custom interval
Compared to Timer , asyncAfter(deadline:) is more light-weighted.
var isTimeOut = true
DispatchQueue.main.asyncAfter(deadline: .now() + timeOut) {
if isTimeOut{
// do time out thing
}
}
check isTimeOut according to WKNavigationDelegate
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
isTimeOut = false
}

Resources