Is this technical solution reasonable about WKWebView on cross-domain issues ?
Hi,all
My project use WKWebView to load offline package, such as .html/.css/.js,and also request some resources from remote server to update pages. So there is a cross-domain problem with local file(file://***) and remote domain (https://***), is this following technical solution reasonable to fix this problem:
1. Create a custom URLSchemeHandler which conforms to WKURLSchemeHandler
2.Unify local file and remote domain request to https request
3. Hook WKWebView https request
4. Implement WKURLSchemeHandler delegate method
(void)webView:(WKWebView *)webView startURLSchemeTask:(id)urlSchemeTask {
NSURL *url = urlSchemeTask.request.URL;
if ([url.pathExtension isEqualToString:@"html"]) {
NSData *data = [[NSData alloc] initWithContentsOfFile:localFilePath];
NSMutableDictionary resHeader = [NSMutableDictionary new];
[resHeader setValue:@"" forKey:@"Access-Control-Allow-Origin"];
[resHeader setValue:@"charset=UTF-8" forKey:@"Content-Type"];
[resHeader setValue:@"text/html" forKey:@"Content-Type"];
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc]
initWithURL:url statusCode:200 HTTPVersion:@"HTTP/1.1" headerFields:resHeader];
[urlSchemeTask didReceiveResponse:response];
[urlSchemeTask didReceiveData:data];
[urlSchemeTask didFinish];
} else {
NSURLSession *defaultSession = [NSURLSession sharedSession];
NSURLSessionTask *dataTask = [defaultSession dataTaskWithRequest:urlSchemeTask.request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
[urlSchemeTask didReceiveResponse:response];
[urlSchemeTask didReceiveData:data];
[urlSchemeTask didFinish];
}];
[dataTask resume];
}
}
Is this technical solution reasonable? and is there any issues that I haven't considered?
Sincerely,
Looking forward to your reply
WebKit JS
RSS for tagAccess and modify DOM elements within a webpage, including touch events and visual effects, using WebKit JS.
Posts under WebKit JS tag
61 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I am currently publishing an application that uses WebView,
I am currently publishing an application that uses WebView, but I am having trouble with data in LocalStorage sometimes disappearing.
The website displayed in WebView is made with PHP,
By writing the following code in JavaScript,
When WKWebView is opened, localStorage is saved and retrieved.
window.localStorage.setItem('isAlreadyAgree', true);
window.localStorage.getItem('isAlreadyAgree');
The problem is that sometimes this getItem does not get the data.
・This is not reproducible and does not always occur when some process is performed.
・Is it possible that the storage of the application is cleared due to distribution using MDM?
・Is it possible to store too much data in UserDefault, which would cause the LocalStorage space to be overwhelmed and disappear?
I would appreciate any hints you can give me.
Thank you in advance.
The app gets stuck after login on an iOS 18 device. It works in Xcode, but the simulator shows the following console error: IntegrationApp(769,0x1f0094c00) malloc: xzm: failed to initialize deferred reclamation buffer (46).
The specification states that the timestamp property is a DOMHighResTimeStamp which always represents a value in milliseconds. However, in my testing (on iOS as I don't have a mac) the timestamp is given as seconds. This could break compatibility if an app/library is not tested in Safari.
Worse is that the deviation seems to be undocumented as every compatibility chart states full compatibility and defines the property as milliseconds.
Any workaround would also be up to one frame incorrect. So a stutter can affect input accuracy.
I know this might seem small but it could mean that an app or game is unplayable in Safari if it relies on this for input.
When I run the following code in XCode iOS Simulator on Safari (connecting via Safari DevTools):
navigator.serviceWorker.ready.then((reg) => reg.pushManager.subscribe({ userVisibleOnly: true, applicationServiceKey: "..." }).then((sub) => console.log(sub.toJSON())))
I get the response:
{ keys: { p256dh: "", auth: "" } }
But I'm expecting p256dh and auth (and endpoint) to be filled out. Why is it not?
Hello everyone,
in my website I need to give users the ability to choose a color via input type=“color”.
I don't understand why it works fine on desktop (even on Safari for Mac) but doesn't open the color picker on iPhone.
How can I solve this?
Thank you,
Andrea
iOS18 Added support for WebRTC HEVC RFC 7789 RTP Payload Format. (112001659),How can i determine whether iOS 18 WebRTC uses hardware or software decoding for HEVC?
Since iPadOS 18.x WKWebView seems to have a bug within its Fullscreen API (which can be enabled via WKPreferences.isElementFullscreenEnabled). This bug has the effect that websites trying to make an element (for example a video player) fullscreen fail to do so. This does not always happen, most of the time the fullscreen mode does work fine, but sometimes (far too often to be ignored) it does not. If an instance of WKWebView shows this issue, it can not be "fixed" by reloading the page or loading other pages, this issue exists in this instance forever.
My App is a web browser App so I can create and remove WKWebView instance easily (by opening or closing Tabs). And there are times where I never see this bug, and times where ever other tab shows this bug. It's totally unreliable.
The App does not show any issues at all when running under iPadOS 17 or older. The issue is only present under iPadOS 18.x.
After some testing I've found out that when the bug has affected an instance of WKWebView, the JavaScript call element.requestFullscreen() will work if the element is a video element, but does no longer work if it is another element (like a DIV). If an instance of WKWebView is not affected by this bug, element.requestFullscreen() will work for all HTML elements.
Does anyone has experienced this bug as well? And maybe found a workaround? Or maybe found a pattern which helps to find out what exactly is triggering this bug?
Recently, we ran into a bit of a problem when using WKWebView. Sometimes, problems with all pages blank occur which use WKWebView.
I implemented WKNavigationDelegate and found that it stops at
- (void)webView:(WKWebView *)theWebView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
and it won't call below func forever
- (void)webView:(WKWebView*)theWebView didStartProvisionalNavigation:(WKNavigation*)navigation
I suspected that the render process is terminated and it won't restart.
Then i try to resolve this problem by call reload func
[self.webView reload];
But it didn't work. In The Meanwhile, i got some error message in console
I have tested it in iOS 16 and 17. only iOS 17 got the issue.
Pray for some help. Thanks a lot.
I'm working on a rather complex web application that includes 3D terrain, 2D mapping, and SVG animations. Both Safari and the Swift app I've built using WkWebKit reload the page after some period of time. Safari pops up a small text block that says:
This webpage was reloaded because it was using significant memory.
Yes. That's true. It's also true that the M1 Max Mac was in now way experiencing issues, nor were any of the other web pages running in other tabs or windows.
The memory limit is simply too low for modern web apps. So far I've not found any way to adjust the parameters in Safari or WkWebView.
Apple, help a brother out. It's not 1997 anymore. Web apps are big. And resetting them at some arbitrary point causes more problems that is solves.
Anyone have any suggestions? Quinn, any way (other than casting a stone into the one-way abyss of Radar) of getting help from the big A here?
I'm developing an application that utilizes WKWebView to display a webpage. My goal is to improve the performance and loading speed of this webpage by intercepting specific API calls and providing pre-stored JSON responses directly from within the app, ensuring the webpage renders instantaneously.
The challenge I am encountering is the inability to intercept HTTPS URL schemes directly from WKWebView. Any insights or solutions from the community on how to effectively manage and overwrite these particular network requests would be greatly appreciated.
I'm injecting some javascript into a WKWebview on iOS. At a certain point the web view spits out these warnings into the console and the javascript execution stops.
0x109018c40 - [PID=778] WebProcessProxy::gpuProcessExited: reason=IdleExit
0x109019200 - [PID=779] WebProcessProxy::gpuProcessExited: reason=IdleExit
Failed to terminate process: Error Domain=com.apple.extensionKit.errorDomain Code=18 "(null)" UserInfo={NSUnderlyingError=0x303c3c060 {Error Domain=RBSRequestErrorDomain Code=3 "No such process found" UserInfo={NSLocalizedFailureReason=No such process found}}}
I can't find any solution for this so am looking if anyone has any idea of what to try.
None of the WKWebview delegate functions trigger when this occurs so I can't attempt to reload the webview at this stage
I am trying to access a camera from web view and I'm unable to load the updated UI in web view and web view gets flick for every few seconds. The updated UI has some more functionality, but the web page not getting loaded.
Running a web server on localhost is breaking on the iOS Simulator. It is also blocking me from testing my mobile application.
Full Log:
Full Log
PLATFORM AND VERSION
iOS
Development environment: Other: Xamarin iOS App
Run-time configuration: iOS 14.4.2 and above
DESCRIPTION OF PROBLEM
We are using WKWebView control in our application. It loads a page, wherein there is a code which gets triggered to execute a Synchronous Ajax/XmlHttpRequest. This request needs about 1 min time to complete, but it gets aborted after 10 secs.
Observed in iPhone 6S 14.4.2. Also seen the same behavior in the latest version of iPhone and iPad OS.
Need help on the below points:
How can I extend this timeout?
Making it an Asynchronous call would have regression. Hence the ask for any other alternative to extend this timeout.
STEPS TO REPRODUCE
In the WKWebView have a webpage, which gives a Synchronous ajax/XmlHttpRequest call to a Web API, which takes more than 10 seconds to complete. The Ajax call sample code is as below, which uses jquery:
var startTime = performance.now();
$.ajax({
async: false, // Synchronous ajax call
type: "POST",
url: "http://testsite:8000/api/RunTestTimer",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
timeInSeconds: 15
}), // timeInSeconds is the parameter name in the Web API, which I used to run a timer on the server-side for the value passed to the ajax call
dataType: "json",
beforeSend: skelta.forms.utilities.addRequestHeaders
})
.done(function (result) {
var endTime = performance.now();
var message = "Request Successful (Time Taken to execute: " + ((endTime - startTime) / 1000).toFixed(3) + " secs; Type: " + "POST" + "; Async: " + "FALSE" + "; Timer: " + "15" + " seconds):" + JSON.stringify(result);
console.log(message);
})
.fail(function (result) {
var endTime = performance.now();
var message = "Request Failed (Time Taken to execute: " + ((endTime - startTime) / 1000).toFixed(3) + " secs; Type: " + "POST" + "; Async: " + "FALSE" + "; Timer: " + "15" + " seconds):" + JSON.stringify(result);
console.log(message);
});
Since iOS 18.1 launched as a beta, we've been getting reports from end users on iPhone 15 Pro and iPhone 15 Pro Max specifically. They're reporting that our WebView is unable to load our local HTML content. I'm curious if anyone else has had their app or users run into this issue?
So far I've tried installing the most recent XCode Beta 16B5014f and installed an 18.1 emulator, but our app worked fine. It's also working fine on all my real devices, but we don't have a 15 Pro to test on. I'm curious if this is related to the processor on these devices and how they are intended to support Apple's new AI coming in 18.1.
We're developing a service that requires webtransport support in the browser. Currently, the only browser that doesn't provide support is the IOS version of Safari.
Our current way forward for client use is to flag iphone and ipad as non compliant and recommend either desktop use or android.
Is there any ballpark date as to when WebTransport will be included in IOS Safari (- webkit supports webtransport)?
I am experiencing an issue with my app, which includes a WKWebView used for displaying and playing WebRTC content (audio and video). Everything works fine on macOS, but on iOS 18, while the video is displayed correctly, there is no sound.
I am wondering if this could be related to privacy permissions on iOS. Could you please clarify if there are any specific privacy permissions I need to address?
I would like to confirm:
AVAudioSession.sharedInstance().setCategory requires any special configuration for WebRTC audio. Are there any particular settings needed for this? My setting codes are below:
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, policy: .longFormAudio)
Do the JavaScript codes in the HTML file require any special handling to ensure WebRTC audio works properly on iOS?
const audioRender = document.createElement('audio');
audioRender.id = 'xxxid';
audioRender.srcObject = streamSource;
audioRender.autoplay = true;
audioHolder.appendChild(audioRender);
Does WKWebViewConfiguration need any specific parameter adjustments to ensure audio playback in WebRTC works as expected?
let webViewConfiguration = WKWebViewConfiguration()
let contentController = WKUserContentController()
contentController.add(self, name: "***")
webViewConfiguration.userContentController = contentController
webViewConfiguration.allowsInlineMediaPlayback = true
We as a team of engineers work on an app intended to visualize medical images. The type of situations where the app is used involves time critical decision making for acute clinical conditions. Stability of the app and performance are of almost importance and can directly help timely treatment action. The app we are developing uses Javascript. It has been observed the footprint of the app is lagging by 2 to 3 seconds in releasing memory while javascript is expecting the memory to be cleared. This is affecting the stability of our application and preventing us in delivering the right quality of application.
The problem specifically can be described as follows, using javascript create an array and then remove it and after removal of the array, create a new array of the same size immediately and again remove it. Because the memory is not released in time, if you repeat these steps a few times the app memory footprint will increase and that crashes the app.
To reproduce this scenario, we have created a simple app which creates an array with size of 100MB and checks the memory footprint using the Xcode instrument tool.
When we create an array of 100MB size, sometimes it shows the memory footprint peak of around 700MB-800MB and when we clear the array by assigning it with an empty array it releases the memory after 2-3 seconds.
Considering the critical nature of the app, I urge you to look into this and provide necessary support and resolution.
Please refer below sample code that will help to reproduce the mentioned scenario.
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
@IBOutlet var webView: WKWebView!
let myHTML = """
<!DOCTYPE html>
<html>
<head>
<style>
.button-style {
width: 400px;
height: 200px;
margin: 15px;
font-size: 50px;
}
</style>
</head>
<body>
<button type="button" class="button-style" onclick="loadDataInCache()">Load Data In Cache</button>
<button type="button" class="button-style" onclick="removeDataFromCache()">Clear Cache</button>
<script>
const size = 1024 * 1024 * 100;
let numberArray = [];
function loadDataInCache() {
numberArray = Array(size).fill(0);
}
function removeDataFromCache() {
numberArray = [];
}
</script>
</body>
</html>
"""
override func viewDidLoad() {
super.viewDidLoad()
// self.view.addSubview(webView)
webView.loadHTMLString(myHTML, baseURL: nil)
}
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
}
Safari cannot open the page due to the error 'WebKit encountered an internal error.' We are using https://github.com/stleamist/BetterSafariView.git, and it was working fine before we updated to Xcode 16.