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.4k 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
777 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
916 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.7k 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.3k 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.4k 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
0 Replies
633 Views
I'm using regular expressions to remove non-latin and non-emoji characters from strings. As Unicode character class escapes (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape) are now widely supported, I used them to simplify my expressions. const regex = new RegExp('[^(\\d\\s\\p{Script=Latin}\\p{gc=Punctuation}\\p{Extended_Pictographic})]+', 'gui'); function removeUnsupportedChars(txt: string) { return txt.replace(this.characterEx, ''); } This works on PC and on Android. However, on iOS, when using this regular expression, emojis get corrupted and shown as squares. I created a minimal CodePen https://codepen.io/lizozom-the-sans/pen/GRYxOzp where the scenario is reproduced with a simplified regex and it seems like on iOS any usage of negation on the Extended_Pictographic class (or any of the other emoji classes) leads to their corruption. Is this a known issue on iOS? Any known workarounds (other than using explicit emoji lists)?
Posted
by
Post not yet marked as solved
1 Replies
528 Views
We have confirmed the title issue on iPads with at least IOS16 or later. window.addEventListener('keydown', e => { e.preventDefault(); e.stopPropagation(); console.log(JSON.stringify(e, ['key', 'altKey', 'ctrlKey', 'shiftKey', 'metaKey'])); }) When a key is pressed in the above code, the console outputs what is being pressed now. However, when the meta key is pressed, "a" does not respond. In addition to this, all other key pairs in the shortcut list displayed by long-pressing "command" do not respond. Is there any way to work around this problem?
Posted
by
Post not yet marked as solved
0 Replies
435 Views
I am trying to implement Safari Web Push using the document to setup APNS and receive silent push messages on a react app on Safari browser. At this point, I have added an endpoint to get push packages on calling window.safari.requestPermission. This prompts the user to enable notification and grants the permission and returns with a device token. I have a server-side node script implemented using node-apn to send a silent push message to the client using a device token. The send function resolves with a successful response. Sample message packet that I am sending via APNS: { "aps": { "content-available": 1 }, "customData": "custom data", "topic": "web.push.ID" } I am expecting the payload to be delivered to the client through an event. I am trying this with the below function on the web page. window.addEventListener('push', function (event) { if (event && event.push) { const payload = event.push; console.log('safari received payload in window.addEventListener:', payload); } }); However, I do not see any message coming to the client. Can someone please point me to what I am missing here? Thanks a lot for your help in advance.
Posted
by
Post not yet marked as solved
1 Replies
801 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
640 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
717 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
499 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