JavaScript

RSS for tag

Discuss the JavaScript programing language.

JavaScript Documentation

Posts under JavaScript tag

66 Posts
Sort by:
Post marked as solved
9 Replies
7.6k Views
I am trying to run JavaScript only after the page has loaded, and according to here - https://developer.apple.com/documentation/safariservices/safari_app_extensions/injecting_a_script_into_a_webpage, I should use DOMContentLoaded. However, it does not seem to work. This is my content.js file: function runOnStart() {     document.addEventListener('DOMContentLoaded', function(e) {         document.body.style.background = "rgb(20, 20, 20)";         document.html.style.background = "rgb(20, 20, 20)";                var divElements = document.body.getElementsByTagName('div');         for(var i = 0; i < divElements.length; i++) {             let elem = divElements[i];             elem.style.background = "rgba(255, 255, 255, 0.05)";         }     }); } runOnStart(); If I take the code outside of the event listener, it runs fine, but a lot of the elements haven't loaded in yet so it doesn't work as it should. The function is definitely running, but the event listener simply doesn't work. I appreciate any help you can give!
Posted
by
Post not yet marked as solved
2 Replies
819 Views
Is it possible to get 240Hz Apple Pencil events in Javascript? I know that with UIKit you have to poke at coalesced events to get this sort of sampling frequency, but it appears that Safari (and Mobile Safari) do not support the new PointerEvents.getCoalescedEvents() API (https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/getCoalescedEvents). Anyone know of another way to get high-frequency 240Hz Apple Pencil events (e.g. as touchmove or pointermove events)?
Posted
by
Post not yet marked as solved
3 Replies
2.9k Views
Hi guys, I have built a PWA that calls the javascript API navigator.geolocation.getCurrentPosition which prompts the user for location access when the Safari permission is set to Ask. This is the correct behavior and works as expected when open in Safari. However when added to the Home Screen and running with a display mode of "standalone", the location alert does not open on my phone (iPhone 13 mini / iOS 15.1.1). And the call never times out. Then if I switch from the PWA to Safari the location alert / prompt is suddenly showing in Safari. So it seems that the alert is targeting the wrong "tab". This does not happen if the PWA display mode is "browser" or "mimimal-ui" with either of those it behaves normally. I can only replicate this on my phone (iPhone 13 mini / iOS 15.1.1). I have also tested on various older phones (15.1.1 and 14.7) as well as several emulators and they all behave as expected. It is possible this is a obscure setting on my phone but it does feel a lot like an iOS Safari bug.
Posted
by
Post not yet marked as solved
1 Replies
945 Views
Greetings to all fellow front-end coders. I have quite a headache because of Apple's autoplay policy. As you've probably experienced, you can't autoplay a video / audio element with sound without user interaction. (I'm referring to this) I'm currently trying to create my own music web application that will support playlists. I work with the Next.js framework and use react-player as player. Since it does not natively support playlists, I created a two-player pendulum system, where one plays the current sound file and the other loads the next. Then their roles change. Everything works great in all browsers, except those on iOS, because this player uses autoplay to start playing. I've been worried about this for several days. I've already thought about letting an Apple product users press play button every time a song changes as a punishment, but of course it's not a good solution. I think a lot of you have encountered this and you have certainly found a solution. Please help me :(
Posted
by
Post not yet marked as solved
2 Replies
1.5k Views
I would like to create a web app where you can drag and drop emails from Apple Mail (on macOS). When you drag emails to the desktop an .eml file is created, but when you drag emails to the browser no file is being transferred, I can only get the mail’s subject. So is it possible to drag and drop emails from Apple Mail to browsers? And if yes, then how? So far I've tried chrome and safari, but neither got any files with the dragged element. On windows with outlook or thunderbird this wasn’t an issue, so I hope it can be done with apple mail as well. Thanks in advance
Posted
by
Post not yet marked as solved
2 Replies
1.8k Views
The current state of testing promotional codes in IOS is not developer friendly in the slightest. I have been trying to implement and test promo codes for a couple months now, while having the store kit integration helps slightly to mimic offer code redemption there is no friendly way of testing offer codes in test flight. I have it implemented with presentCodeRedemptionSheet() it seems the easiest way to test the codes is release my app to production create a 3-day promo which is the minimum amount of days that can be set, then wait 3 days before I can test again in different ways. One of my colleagues who is not a developer also wanted to test this feature and it did not work for her. Unfortunately it was a month long promo code she had redeemed so will have to wait till September to see if this is fixed for her now. I have also must note the fact the code redemption sheet and setting up payments in apple all together is a buggy mess. Starting out I added my card via apple pay thinking this would be enough to go through the redeem code process. Then upon entering my code it would show the dialog to verify with touch ID along with my payment details and even a picture of my card. After verifying, it then kept showing a pop up that I must include payment information which I already had added via apple pay. In the end to fix this I had to remove the payment method restart the device, add the payment method again then restart the device again. Another issue I bumped into is when you press redeem the "redeem offer" button is disabled but nothing happens for a while until it appears to timeout and you have to try again until it eventually works. The final annoyance I experienced was creating the offer code for my subscription and immediately trying to redeem it apple said the offer expired even though i set it to the 31st of August and the date was the 2nd. Only way to fix this was once waited and keep trying banging your head against the wall until it eventually works. In summary, I hope apple have a review of their offer code redemption process and make it more developer friendly and implement a way of testing within test flight whether it use live offer through test flight or include a new section to add test offer codes for subscriptions.
Posted
by
Post not yet marked as solved
2 Replies
1.7k Views
I have a chrome extension that was converted to Safari extension using xcode safari-web-extension-converter utility. With that, everything except one thing seems to be fine. In the background script, I am loading some data from a web accessible resource like so: export const fetchConfig = async () => { let dataURL = ''; if (!checkBrowser(BROWSERS.Chrome, true)) { dataURL = chrome.runtime.getURL('config.json'); } else { dataURL = browser.runtime.getURL('config.json'); } const res = await fetch(dataURL); return await res.json(); } This works for all browsers except Safari. Where I am getting the runtime URL as: safari-web-extension://E522689D-94A6-4561-90F3-BF22C7848965/config.json but the fetch call fails with the error: Failed to load resource: unsupported URL I have not been able to find anything on this in the documentation, but can we not access the web accessible resources in background in Safari? My manifest file looks like this: { "manifest_version": 3, "name": "Ext Dev", "author": "Test", "description": "Test", "version": "1.1.0", "icons": { "16": "assets/icon/icon16.png", "32": "assets/icon/icon32.png", "48": "assets/icon/icon48.png", "128": "assets/icon/icon128.png" }, "host_permissions": [ ... host addresses here ... ], "permissions": ["storage", "tabs"], "content_security_policy": { "extension_pages": "script-src 'self'; object-src 'self';" }, "web_accessible_resources": [{ "resources": ["config.json"], "matches": ["<all_urls>"] }], "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"], "css": ["commonstyles.css"], "run_at": "document_end", "all_frames": true } ], "background": { "service_worker": "background.js" }, "action": { "default_title": "Ext Client", "default_icon": { "20": "assets/icon/icon20.png", "40": "assets/icon/icon40.png" } }
Posted
by
Post marked as solved
4 Replies
1.8k Views
I'm using manifest v3 and working on a Safari extension. When I try to run a function within activeTab. I can not get the proper return from the the function. For example: browser.scripting.executeScript({ target:{tabId:tab.id}, func:()=>'test', }).then(result=>{ console.log('result',result) }) Here the result is always null. Is it a bug? Nothing wrong with permission settings because if I use files instead of func, the return value works properly. Safari: Version 16.1 (18614.2.3.1.1) macOS 13.0 Beta Xcode: Version 14.0 beta 5 Thanks
Posted
by
Post not yet marked as solved
25 Replies
5.4k Views
Open music.yandex.ru Open browser console Paste this code: navigator.mediaSession.metadata = new MediaMetadata({ title: "11111111111", artist: "222222222", album: "3333333333", artwork: [ { src: "https://avatars.yandex.net/get-music-content/5375761/c8e05100.a.19837155-1/200x200" } ]}); Open Now playing widget. Title, artist, album is set correctly. Cover not set. macOS 13.0.1 (22A400) Safari 16.1 (18614.2.9.1.12) Note! In macOS 12.6.1 Safari 15.6.1 (17613.3.9.1.16) all works as expected.
Posted
by
Post not yet marked as solved
1 Replies
1.5k Views
I am using the code below to ask for location permission only for iOS devices when the component renders, below is the code snippet: if (!!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)) { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( success => { if (success) { const coords = { lat: success.coords.latitude, lng: success.coords.longitude, }; this.fetchNearestLocation(coords); this.setState({ showCurrLocationMarker: true }); this.setState({ isCurrentLocationBlocked: false }); } }, error => { if (error && error.code) { this.setState({ showCurrLocationMarker: false }); this.setState({ isCurrentLocationBlocked: true }); } }, ); } } The issue here is that once the location access is blocked for Safari browser from the settings, and after sometime it is enabled again, I won't get the location permission popup at all. I am confused whether the issue is related to the code or the browser (settings). I was expecting to get a location permission pop-up on when the component renders on an iOS device on Safari browser.
Posted
by
Post not yet marked as solved
1 Replies
823 Views
Hey, I read the guidelines of the App Store and saw that repackaged website will be declined. Buts, an ionic application is basically a wrapped website and PWA as well. So I don't really understand the guidelines. Is there someone or somewhere I cam message to ask and get a formal answer? Thanks in a advance.
Posted
by
Post not yet marked as solved
0 Replies
661 Views
I am new in the MAC Catalyst development. I have one application that is developed by using electronjs. This app is having the functionality of SIP/VoIP. Audio/Video calling works well. But I want to implement the screen sharing functionality. I have tried to implement it but I was not able to do it. I have tried the below stuff: navigator.mediaDevices.getUserMedia(options) : It was giving error "Uncaught (in promise) DOMException: Not supported". desktopCapturer.getSources : Not able to get streams. I have written the logic to get streams in the preload.js file. I am not able to get streams and suppose in case, I have got the streams, How can I load that on the video element that is not rendered yet? Because the preload file is executed before the loading of the window. So It's giving the error 'Cant read property 'srcObject' of undefined''. ipcRenderer & ipcMain : Giving the same result as above. AVFoundation : Only working for the mobile apps. So my question is, Is there any way to share the screen in the MAC Catalyst apps by using electronjs or by using any other way? If so, Please refer.
Posted
by
Post not yet marked as solved
0 Replies
745 Views
I have electronjs app for the MAC Catalyst. I have implemented audio/video calling functionalities. Those works well. I have also implemented functionality to share the screen by using below code. navigator.mediaDevices.getDisplayMedia(options).then((streams) => { var peer_connection = session.sessionDescriptionHandler.peerConnection; var video_track = streams.getVideoTracks()[0]; var sender_kind = peer_connection.getSenders().find((sender) => { return sender.track.kind == video_track.kind; }); sender_kind.replaceTrack(video_track); video_track.onended = () => { }; }, () => { console.log("Error occurred while sharing screen"); } ); But when I hit the button to share the screen by using above code, I am getting below error. Uncaught (in promise) DOMException: Not supported I have also tried navigator.getUserMedia(options,success,error). It's supported by the Mac Catalyst desktop apps. But it's only giving the streams of the webcam. I have also checked online if navigator.mediaDevices.getDisplayMedia(options) is supported in the Mac Catalyst or not. It's supports in the Mac Catalyst. But still I am facing this issue. I have also tried with the desktopCapturer API of the electronjs. But I don't know how can I get the streams from it. //CODE OF 'main.js' ipcMain.on("ask_permission", () => { desktopCapturer .getSources({ types: ["window", "screen"] }) .then(async (sources) => { for (const source of sources) { // console.log(source); if (source.name === "Entire screen") { win.webContents.send("SET_SOURCE", source.id); return; } } }); }); I have tried to get streams by using the below code in the preload.js. But I was getting the error Cannot read property 'srcObject' of undefined. window.addEventListener("DOMContentLoaded", (event) => { ipcRenderer.on("SET_SOURCE", async (event, sourceId) => { try { const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: "desktop", chromeMediaSourceId: sourceId, minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720, }, }, }); handleStream(stream); } catch (e) { handleError(e); } }); let btn = document.getElementById("btnStartShareOutgoingScreens"); btn.addEventListener("click", () => { if (isSharing == false) { ipcRenderer.send("ask_permission"); } else { console.error("USer is already sharing the screen.............."); } }); }); function handleStream(stream) { const video = document.createElement("video"); video.srcObject = stream; video.muted = true; video.id = "screenShareVideo"; video.style.display = "none"; const box = document.getElementById("app"); box.appendChild(video); isSharing = true; } How can I resolve it. If this is not supported in the MAC Catalyst, Is there is any other way to share the screen from the MAC Catalyst app by using WebRTC.
Posted
by
Post not yet marked as solved
0 Replies
537 Views
Whenever the mic is turned on on an iOS device using Chrome browser, a popup saying "Microphone Access Allowed" appears. Chrome does not have any documentation/blog regarding the popup. All it has is the support page at https://support.google.com/chrome/answer/2693767?hl=en&co=GENIE.Platform%3DiOS&oco=1 that says: ... When prompted, tap Allow or Don't Allow. To immediately edit your preference, tap Edit. I have a web app that turns microphone on/off frequently which results in the said popup appearing constantly ruining the UX. Is there any way to fix this? Say, for example, make it appear only once, better, disable it altogether? I understand that Chrome is doing it to catch user's attention that an app is accessing the microphone. But in my case, the UX suffers greatly when the core of my app involves using microphone. This happens only on iOS. Has anyone have had similar experience before?
Posted
by
Post not yet marked as solved
0 Replies
860 Views
[Ticket on Feedback Assistant FB12353357] Hi there, We’re experiencing issues playing explicit songs using MusicKitJS for the Web (tested on both stable v1 and beta v3). Upon calling the SDK’s “play()” function, the following error gets logged in the console “CONTENT_RESTRICTED: Content restricted” and playback doesn’t begin. The Storefront we’ve tested in is “it”, but very likely all of them are impacted with the issue, here’s a few Adam IDs of affected tracks: 1681182396, 1683117248, 1669607876. A quick check with the REST APIs reveals indeed that the relevant thing all 3 of them have in common is "contentRating" being "explicit”. The bug isn’t however easy or predictable to replicate because it seems that it can be somewhat solved by fiddling with both the “Screen Time” restrictions settings within an iOS/iPadOS device (of course logged in with the same Apple account), as well as with the “Parental Controls” dashboard located in the Web version of the Apple Music’s settings page. We’re still not 100% sure what exactly “triggers” the fix, but both mentioned dashboards above are essential in attempting to solve it by trial and error. Specifically: in the “Parental Controls” dashboard what helps is actually turning ON the restrictions with the toggle, and then easing them up the most by specifically setting the less restricted available option in all 3 dropdown menus (pretty baffling); in the “Screen time” dashboard what helps is simply enabling/disabling the feature itself altogether, as well as the “Content & Privacy restrictions” toggle, and changing the level of allowed content between “Clean” and “Explicit”; I also want to highlight the fact that during the entire process, for the issue to be actually solved, users every time had to to restart their iPhone/iPad multiple times after changing a setting in “Screen time”, along with deauthorizing/authorizing (logging out and back in) their Apple Music account from the MusicKitJS SDK. The issue seems to always affect freshly created Apple accounts right from the start, we’re not aware of methods that can lead to the bug “coming back” and starting to happen again after being solved manually with the process above (meddling “randomly” with dashboards). It’s a pretty serious one because many of our users do not posses an Apple device and only use their Apple Music subscription on the Web and/or their Android device, meaning that the “Screen time” dashboard isn’t available for them. We’ve never been able to solve the problem on an Apple ID account solely by fiddling with the “Parental Controls” dashboard located in the Web version of the Apple Music’s settings page: tinkering with the “Screen time” settings was essential every single time, meaning owning an Apple device is essential to solve it. Last thing I’m adding is that the issue doesn’t seem to also affect listening to these explicit songs directly with the various first-party Apple Music clients (tested on the iOS native app, Android native app, and on the Apple Music WebApp). Steps to reproduce: on the Web, create a new Apple ID account and activate an Apple Music subscription (do not login with said account on an Apple device); go to the Apple Music WebApp settings page at music.apple.com/account/settings and make sure that the “Parental Controls” restrictions are turned OFF; open any explicit song in the Apple Music WebApp and confirm that playback is allowed; login and authorize the newly created account using any website/application integrated with the MusicKitJS SDK (v1 or v3, doesn’t matter); open the same explicit song as before (or any other) in said third-party client that uses the SDK and verify that playback doesn’t begin and an error “CONTENT_RESTRICTED: Content restricted” is logged in the console upon playing. Additional infos: Apple ID account region and language: Italy - Italian; Storefront affected: IT but possibly all of them; MusicKitJS versions affected: both v1 and v3; Browser where the issue was reproduced: Chrome v114. Attached you’ll find some informational screenshots. Thanks!
Posted
by
Post not yet marked as solved
0 Replies
738 Views
Hello, I would reply to this post but the reply button is broken in Chrome and Firefox on Linux..... If I am out of date or have misunderstood then please accept my apologies in advance. I want to do make the following custom element in Safari but it is apparently not currently supported for "ideological" reasons ? class my_special_element extends HTMLInputElement { myCustomFunction(){ self.value="Oh look, I have extended the element class with a new method"; } } //Then in HTML <input is="my-special-element"> I can already, easily extend web components in Safari right now by doing the following - as I have been doing for the past 15 years in all browsers. function my_special_element_pretend_class(element) { self=element; self.myCustomFunction=function(){ self.value="Oh look, I have extended the element class with a new method"; } return self; } //In this case myElement is an "input" element. var myElement = document.getElementById('myElement'); myElement=my_special_element_pretend_class(myElement); myElement.myCustomFunction(); Given that this is so unbelievably easy to do, why is Apple adopting a stance at odds with the W3C over Web Components ? If you're HONESTLY worried about namespace collisions then surely just throw an exception ? Don't we already have to stay on top of bugs caused by new features etc ? Security ? Really ? Please read the code above again ! Surely you'd have to fundamentally alter the core extensibility of Javascript to keep yourself safe from that ? We all breathed a massive sigh of relief when Microsoft killed IE11. Is Safari going to become the hated reason for another zillion bloated, resource consuming polyfills that slow down the UI ONLY on YOUR devices ? Best wishes Chris
Posted
by
Post not yet marked as solved
0 Replies
828 Views
Hello everyone, I've been working on implementing push notifications for the web PWA using JavaScript, and I've encountered an issue specifically with Safari on Mac and iOS devices. While my code snippet works perfectly fine in Chrome, I'm facing a problem with the clients.openWindow function. It doesn't seem to perform any actions or provide any errors. Here's the code snippet for reference: self.addEventListener('push', (event) => { const notification = JSON.parse(event.data.text()); console.log(notification); const title = notification?.notification?.title; const body = notification?.notification?.body; const data = notification?.data; const options = { body, data, icon: '/favicon.ico', badge: '/favicon.ico', vibrate: [100, 50, 100], actions: [ { action: onNotificationAction(notification['data']), title: notification.notification.title, }, ], }; event.waitUntil(self.registration.showNotification(title, options)); }); self.addEventListener('notificationclick', (event) => { console.log(event, 'event'); const notification = event?.notification; event.notification.close(); event.waitUntil( clients .matchAll({ type: 'window', }) .then((clientList) => { for (const client of clientList) { if (client.url === '/' && 'focus' in client) return client.focus(); } if (clients.openWindow) return clients.openWindow('/messages'); }), ); }); After thorough testing, I've determined that the issue lies specifically with the clients.openWindow function. Unfortunately, I haven't been able to identify any errors or determine why it isn't functioning as expected. The goal is to open a new window or focus on an existing one when a notification is clicked. I would greatly appreciate any assistance or insights into resolving this issue. Has anyone else encountered a similar problem with Safari and iOS? Are there any alternative approaches or workarounds that could achieve the desired functionality? Thank you in advance for your help and suggestions!
Posted
by