JavaScript

RSS for tag

Discuss the JavaScript programing language.

Posts under JavaScript tag

43 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Universal Link Failures in Safari
We encountered an issue with universal links where the link failed to open the iOS application from Safari when triggered by an javascript outside a click event. However, when we modified the code to open the link directly via a user click, the application launched as expected. Based on our testing, this issue seems to occur only when there is information for the application cached in Safari (i.e. IDP page cached, redirects to our app, javascript based universal link navigation fails). Here is a code example of what caused the universal link failure: const openUniversalLink = () => { buttonClicked = True } useEffect(()=> { if (buttonClicked) { window.location.href = universal_link } } <Button onClick={openUniversalLink} /> Here is a code example of what caused our universal links to open successfully: const openUniversalLink = () => { window.location.href = universal_link } <Button onClick={openUniversalLink} /> Are there defined practices of when we are able to open universal links triggered by javascript vs when they must be opened directly through user action?
1
0
108
4d
Can't use Clipboard API after sending a message to the background script?
Hi, I’m encountering an unexpected issue in Safari. Specifically, navigator.clipboard.writeText() fails when called from a content script in my extension immediately after sending a message to background.js while it works fine in Chrome and Firefox. Is this expected? Environment Safari 18.2 (20620.1.16.11.8) Technology Preview 210 macOS Sequoia 15.2 (24C101) Example This is a minimal reproducible example, which adds a button to example.com: https://github.com/mshibanami/ClipboarAPIIssueExample Below is the related code: // content.js copyButton.addEventListener('click', async () => { // 👇️ This call seems to trigger the issue await chrome.runtime.sendMessage({}); try { await navigator.clipboard.writeText(text); alert(`✅ Copied '${text}' to clipboard!`); } catch (err) { alert(err + '\n\n' + `navigator.userActivation.isActive: ${navigator.userActivation.isActive}`); } }); // background.js chrome.runtime.onMessage.addListener(() => { }); When I click the button, I expect the text to be copied successfully. However, I receive an error in Safari.: Interestingly, if I remove chrome.runtime.sendMessage(), the clipboard operation works without any problems. Also, note that navigator.userActivation.isActive is true, which might mean it's not related to the User Activation API. Misc. This might be related to another question I posted here: https://developer.apple.com/forums/thread/772275
0
0
133
1w
Clipboard API `writeText()` fails in Safari due to User Activation API, but works in Firefox and Chrome
Hi, I'm encountering an issue with the Clipboard API's writeText() method in Safari. It throws a NotAllowedError even when triggered by a user action (selecting an option from a <select> element). Is this expected? This issue seems specific to Safari, as the same code works perfectly in Firefox and Chrome. Perhaps I should send feedback to Apple, but I'd like to post it here first in case I misunderstand something. Problem In Safari, when I try to copy text to the clipboard using navigator.clipboard.writeText() within an input event listener attached to a <select> element, it fails with the following error: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission. Environment Safari 18.2 (20620.1.16.11.8) Technology Preview 210 macOS Sequoia 15.2 (24C101) Example I've created a minimal reproducible example on CodePen: https://codepen.io/mshibanami/pen/LEPdxXZ Here's the relevant JavaScript code from the example: selectElement.addEventListener('input', async (event) => { const selectedText = event.target.options[event.target.selectedIndex].text; try { await navigator.clipboard.writeText(selectedText); alert(`Text copied to clipboard: ${selectedText}`); } catch (err) { alert('Failed to copy text to clipboard: ' + err); } }); Firefox and Chrome handle this code without any issues, successfully copying the text to the clipboard, but not Safari. Possible Cause I suspect this issue might be related to WebKit's User Activation API. It seems like Safari is not correctly recognizing the input or change event on a <select> element as a valid user activation for the Clipboard API, even though it is initiated by a user gesture. Questions Is this behavior unexpected? Should Safari allow the Clipboard API to work in this context? (Technically, this might be expected as of now, as such events are not explicitly described in https://webkit.org/blog/13862/the-user-activation-api/.) Any insights or suggestions would be greatly appreciated. Thanks!
0
0
221
1w
Search.autocomplete coordinates vs Geocoder.reverseLookup coordinates are inconsistent and incorrect results
When using Search.autocomplete and getting the results, each search result object has coordinate which have 13 decimal places. When you use Geocoder.reverseLookup for these coordinates, it returns the wrong address and different coordinates (6 decimal places and different as well). What works is using Geocoder.lookup (with getsUserLocation as true) and putting in the Search.autocomplete displayLines (as a string) for the query. Am I doing something wrong or is this a bug? Code: const exampleQuery = '<example address>'; const search = new mapkit.Search({ getsUserLocation: true, }); search.autocomplete( exampleQuery, (error, data) => { if (error) { console.error('Search error:', error); return; } const { coordinate } = data.results[0]; console.log("Autocomplete coordinate", coordinate); // Lat and lng are both have 13 decimal places const geoCoder = new mapkit.Geocoder({}); geoCoder.reverseLookup( new mapkit.Coordinate(coordinate.latitude, coordinate.longitude), (error, data) => { const { formattedAddress, coordinate } = data.results[0]; console.log(formattedAddress, coordinate); // Not the same address from example query and from the search autocomplete, also the coordinate has 7 decimal places } ); }, {} );
0
0
287
Nov ’24
How to paginate PointsOfInterestSearch results in MapKit JS?
I created a PointsOfInterestSearch (https://developer.apple.com/documentation/mapkitjs/pointsofinterestsearch) on the frontend using MapKit JS: const poiSearch = new window.mapkit.PointsOfInterestSearch({ center: new mapkit.Coordinate(userLocation.lat, userLocation.lng), radius: 10000, }); poiSearch.search((error, results) => { console.log("Length of poiSearch:", results.places.length); results.places.forEach((place) => { console.log("Name:", place.name); }); }); The length of results.places is 20. Trying it with a bigger radius also still results in 20. The docs for PointsOfInterestSearchResponse shows only a places (https://developer.apple.com/documentation/mapkitjs/pointsofinterestsearchresponse) and no options for pagination. How can I paginate the rest of the results?
0
0
231
Nov ’24
FaceTime camera returns promise before solving it
The strange_behaviour.mp4 video attached shows how when running a list of statements to open (startCamera) and close (closeCamera) the camera against a MacBook Pro 2019 using the FaceTime camera, these return their value almost immediately, when in reality the camera is still opening and closing. We believe that there might be a queue for statements to run against the camera and it finishes the awaits when all the statements are inserted in the queue instead of when they are actually solved. We also attached the expected_behaviour.mp4 video where we replicate the same flow but using an external camera instead of the FaceTime camera. In this video, the promises take a bit longer to return but they do once the camera has already been opened and closed the requested amount of times. The project used in the videos is attached as project.tar.xz. We would like to know if the behaviour in strange_behaviour.mp4 is replicable on your side and if there is a way to access the cameras to make it behave like when using an external camera (expected_behaviour.mp4). Attachments: https://drive.google.com/drive/folders/1cOeFb5GMbh4mPOeZiZyyevk3N778Kn1M?usp=sharing
0
0
264
Nov ’24
HTML input onChange Event Triggered Multiple Times with Korean Multilingual Keyboard in iOS 18
Description: When using a multilingual keyboard that includes Korean in iOS 18, the input element's onChange event is triggered multiple times instead of just once. This issue occurs not only when entering numbers with input type="tel" or inputMode="numeric", but also when entering text with input type="text". This causes unexpected behavior in forms and other input-related functionalities. Affected Devices and OS Version: Device: iPhone 16 Pro OS Version: iOS 18.0 You can reproduce the issue with this CodeSandbox example: https://codesandbox.io/p/sandbox/elegant-dream-jnqh39 Steps to reproduce: Use a multilingual keyboard (e.g., Korean and English) on iOS 18. Type some text into the input field (input type="text"). Also try entering numbers using input type="tel" or inputMode="numeric". Observe that the onChange event is fired multiple times for both text and numeric input. Expected behavior: The onChange event should only be triggered once when text or numeric input changes. Additional Information: This issue has been reported under feedback ID FB15377631. Currently waiting for a response from Apple regarding this feedback.
0
0
263
Nov ’24
Shape Detection API (Barcode Detector)- Safari 18.X
Hi Folks, do you know what happend with the "shape detection API" feature flag on Safari 18.X (IOs 18.X)?... in previous versions (17.X) i enabled the "shape detection API" feature flag and was able to detect codes like mentioned here... https://developer.mozilla.org/en-US/docs/Web/API/Barcode_Detection_API#browser_compatibility I built a PWA (Service Worker) with Angular 18 and facing this issue immediately after updating to IOS 18.0 (I enabled/disabled the flag, restartet the device several times... no success at all) Do you have an Idea what changed or how i can enable that feature again? Thx a lot in advance.. Cheers Martin
1
1
591
Nov ’24
WKWebView gpuProcessExited IdleExit Code=18
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
0
0
929
Oct ’24
EventSource: event 'error' not fired in iOS18
Hi, I noticed that event 'error' from EventSource is not fired in latest iOS 18, when web application is minimized and then re-activated. This was working in previous versions, so it is probably regression bug. Behavior in iOS 17: PWA application has active SSE/EventSource connection with server. Then some other application becomes active for more then ≈20 sec, so that SSE connection is closed. After SSE connection is closed, application is opened again. When application becomes visible, 'error' event is fired. This is expected behavior and this way also works on other non-iOS systems. Behavior in iOS 18: Following same steps as before it looks like that error event is not fired. Also,readyState of EventSource is 1 (EventSource.OPEN ), even if SSE connection is closed. If connection is interrupted when application is in foreground, then error event is fired on both iOS versions. This is quite problematic, because previously you could rely on 'error' event to trigger reconnection, when application becomes visible, but now this is not possible. Also EventSource readyState is 1, even if there is no connection to the server, so it is in wrong state. Any thoughts?
1
1
431
Oct ’24
FetchEvent.respondWith is terminated in 70 seconds in ServiceWorker
Hi, there. I am trying to use ServiceWorker on iPad to retry a request that has a communication error. However, I am having trouble with the process being terminated after 70 seconds. Occurs at least on iPadOS 17.6.1 and 16.3. The following is the service worker code to reproduce the problem: self.addEventListener('fetch', (event) => { if (event.request.url.includes('test.html')) { event.respondWith(longRunFetch()); } }); async function longRunFetch(request) { await new Promise(resolve => setTimeout(resolve, 75000)); return new Response('Fetch completed'); } When this code is executed on an iPad and a request is made to test.html, the service worker stops after about 70 seconds. When it stops, it falls back to the network request and the contents of test.html are displayed. The service worker thread appears to be killed and is unavailable until the browser is restarted. If timeout is set to 65000, 'Fetch completed' is displayed as expected. Why is the process terminated in 70 seconds? Is there any way to continue processing beyond 70 seconds?
0
0
306
Sep ’24
Cannot Play mp3 File via AudioContext in iOS 18 Safari
I have a Safari extension that plays audio via the javascript AudioContext API. It was working fine under iOS 17 and is now broken under iOS 18. It does not play audio at all. I've tried in both the iOS 18 public beta and the iOS 18.1 developer beta. It is broken in both of them. I've also created Feedback item FB15170620 which has a url attached to a page I created which demonstrates the issue.
0
0
476
Sep ’24
Trouble Generating Client Secret for Apple Sign-In Migration
We're preparing to migrate our Apple Sign-In users for an upcoming app transfer. Following this guide, we're currently stuck on the first curl command: curl -v POST "https://appleid.apple.com/auth/token" \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'grant_type=client_credentials' \ -d 'scope=user.migration' \ -d 'client_id=CLIENT_ID' \ -d 'client_secret=CLIENT_SECRET_ISSUED_BY_TEAM_A' Specifically, we're having issues generating the client secret, specified here. We're using a Node.js script to generate the script; initially I realized that the private key I was signing the JWT with was wrong (I was using the App Store Connect API team key instead of a private key for use with Account & Organization Data Sharing). Every time we try entering this curl command: curl -v POST "https://appleid.apple.com/auth/token" \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'grant_type=client_credentials' \ -d 'scope=user.migration' \ -d 'client_id=com.jumbofungames.platMaker' \ -d 'client_secret=$(node clientsecret_jwt2.js)' Where $(node clientsecret_jwt2.js) is the command to generate the client secret; we get this error: < HTTP/1.1 400 Bad Request < Server: Apple < Date: Mon, 19 Aug 2024 15:41:31 GMT < Content-Type: application/json;charset=UTF-8 < Content-Length: 49 < Connection: keep-alive < Pragma: no-cache < Cache-Control: no-store < * Connection #1 to host appleid.apple.com left intact {"error":"invalid_client","email_verified":false}% Here is the script we are using to generate the Client Secret (JWT), with some variables using placeholders for privacy: const fs = require('fs'); const jwt = require('jsonwebtoken'); // npm i jsonwebtoken // You get privateKey, keyId, and teamId from your Apple Developer account const privateKey = fs.readFileSync("./AuthKey_ABCDEFG123.p8") // ENTER THE PATH TO THE TEAM KEY HERE (private key file) const keyId = "API_KEY"; // ENTER YOUR API KEY ID HERE const teamId = "TEAM_ID"; // ENTER YOUR TEAM ID HERE const clientId = "com.companyname.appname"; // ENTER YOUR APP ID OR SERVICES ID HERE (This is the client_id) // Time settings (in seconds) let now = Math.round((new Date()).getTime() / 1000); // Current time (seconds since epoch) let nowPlus6Months = now + 15776999; // 6 months from now (maximum expiration time) let payload = { "iss": teamId, // The Team ID associated with your developer account "iat": now, // Issued at time "exp": nowPlus6Months, // Expiration time (up to 6 months) "aud": "https://appleid.apple.com", // Audience "sub": clientId // The App ID or Services ID } let signOptions = { "algorithm": "ES256", // Algorithm for signing (ECDSA with P-256 curve and SHA-256 hash algorithm) header : { "alg": "ES256", // Algorithm in the header "kid": keyId, // Key ID in the header "typ": "JWT" // JWT type } }; // Generate the JWT (client_secret) let clientSecret = jwt.sign(payload, privateKey, signOptions); console.log(clientSecret); module.exports = clientSecret; If anyone has run into similar issues using this API or could shed some light on what could be going wrong, please let us know — we're at a bit of a loss here.
1
0
779
Aug ’24
First iOS release crashes on opening
Hello everyone, I'm releasing an Expo React Native app for Android and iOS. The Android release went well, but the iOS build crashes when opening in Testflight and the submission to Appstore crashes as per the review feedback. When I run it locally with ExpoGo it works as expected. Im not experienced in iOS development and my research didn't give me any concrete answers, a hint may be that on the JS code somewhere an object is being used as a boolean in a condition. Can someone point me to the nature of this issue so I can continue debugging? This is the crash log on Xcode when i create a new release: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryM boolValue]: unrecognized selector sent to instance 0x600000230300' *** First throw call stack: (   0   CoreFoundation                      0x00000001804ae138 __exceptionPreprocess + 172   1   libobjc.A.dylib                     0x0000000180087db4 objc_exception_throw + 56   2   CoreFoundation                      0x00000001804c2f88 +[NSObject(NSObject) instanceMethodSignatureForSelector:] + 0   3   CoreFoundation                      0x00000001804b2288 forwarding + 1280   4   CoreFoundation                      0x00000001804b45ac _CF_forwarding_prep_0 + 92   5   ColineleTransilvaniei               0x0000000104e6abbc __41-[RCTModuleMethod processMethodSignature]_block_invoke_12 + 68   6   ColineleTransilvaniei               0x0000000104e6bd88 -[RCTModuleMethod invokeWithBridge:module:arguments:] + 292   7   ColineleTransilvaniei               0x0000000104e6ded0 _ZN8facebook5reactL11invokeInnerEP9RCTBridgeP13RCTModuleDatajRKN5folly7dynamicEiN12_GLOBAL__N_117SchedulingContextE + 456   8   ColineleTransilvaniei               0x0000000104e6db28 ___ZN8facebook5react15RCTNativeModule6invokeEjON5folly7dynamicEi_block_invoke + 112   9   libdispatch.dylib                   0x00000001070d7ec4 _dispatch_call_block_and_release + 24   10  libdispatch.dylib                   0x00000001070d973c _dispatch_client_callout + 16   11  libdispatch.dylib                   0x00000001070e1a30 _dispatch_lane_serial_drain + 916   12  libdispatch.dylib                   0x00000001070e2774 _dispatch_lane_invoke + 420   13  libdispatch.dylib                   0x00000001070ef1a8 _dispatch_root_queue_drain_deferred_wlh + 324   14  libdispatch.dylib                   0x00000001070ee604 _dispatch_workloop_worker_thread + 488   15  libsystem_pthread.dylib             0x0000000105b1b814 _pthread_wqthread + 284   16  libsystem_pthread.dylib             0x0000000105b1a5d4 start_wqthread + 8 ) libc++abi: terminating due to uncaught exception of type NSException PS: I failed to Symbolicate the crash logs as well, but will try again
1
0
421
Aug ’24
contenteditable + getBoundingClientRect() does not return the correct result.
If a sufficiently long text in an HTML tag leads to a text wrap, the calculated values (y and width) of getBoundingClientRect for characters or words directly after the wrap are not correct, if the element or one of a parent is contenteditable="true" the y value has the value as if it were still before the break the width value spans the entire width, Here a code that reproduces this failure: https://stackblitz.com/edit/vitejs-vite-jwghts?file=src%2Fmain.ts,src%2FcalcLetterRects.ts,src%2Fstyle.css
1
0
417
Aug ’24
Dynamic Loading Javascript
Hi, Is it possible to publish an app to the app store which has functionality to download a javascript package that handles UI? I want to have an application that uses a framework such as Capacitor to dynamically download and load a javascript package and to provide updates for bug fixes and improvements on a regular basis. The package will be based off an app we currently use in house. Thanks Nate
0
0
374
Jul ’24
The width and height in MediaStreamTrack.getSettings are incorrect
I run the following code on iOS Safari: const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 960, height: 540, }, }); const { width, height } = stream.getVideoTracks()[0].getSettings(); console.log(`${width} * ${height}`); // 960 * 540 setTimeout(() => { const { width, height } = stream.getVideoTracks()[0].getSettings(); console.log(`setTimeout: ${width} * ${height}`); // setTimeout: 540 * 960 }, 600); The width and height of width and height of the video track obtained by synchronously are different from those obtained by asynchronously. This is my test result and userAgent: Can someone help with this issue?
0
0
531
Jun ’24
JavaScript Not Executing in WebView When Modally Presenting UIViewController on iOS 17.5.1
Issue Summary: I have encountered an issue where JavaScript does not execute in a WebView when another UIViewController is presented modally with modalPresentationStyle.fullScreen. This problem only occurs on physical devices running iOS 17.5.1. The issue is not present on iOS 17.5 simulators or devices running iOS 17.4.1 or earlier. Reproduction Steps: Create a ViewController with a WebView. Load a web page (e.g., https://apple.com) in the WebView. Present another ViewController modally with modalPresentationStyle.fullScreen. Verify that JavaScript execution in the initial WebView stops working. Test Code: import UIKit import WebKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Set up the WebView let configuration = WKWebViewConfiguration() let webView = WKWebView(frame: view.frame, configuration: configuration) view.addSubview(webView) webView.frame = view.frame if #available(iOS 16.4, *) { webView.isInspectable = true } else { // Fallback on earlier versions } webView.load(URLRequest(url: URL(string: "https://apple.com")!)) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let navigationController = UINavigationController(rootViewController: TargetViewController()) navigationController.modalPresentationStyle = .fullScreen present(navigationController, animated: true) } } class TargetViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Set up the WebView let webView = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration()) view.addSubview(webView) webView.frame = view.frame if #available(iOS 16.4, *) { webView.isInspectable = true } else { // Fallback on earlier versions } webView.load(URLRequest(url: URL(string: "https://apple.com")!)) } } Observations: The JavaScript within the WebView stops executing only on physical devices running iOS 17.5.1. This issue does not occur on the iOS 17.5 simulator. Devices running iOS 17.4.1 or earlier do not experience this issue. Request for Assistance: Could you please provide any insights or potential workarounds for this issue? Additionally, if this is a known bug, any information on upcoming fixes would be highly appreciated. Thank you.
3
0
1.2k
Jun ’24