chrome window.load~ .play()
chrome window.load~ .play()
window.onload = function() {
document.getElementById("up").play();
alert("k");
}
<audio id="up" src="./res/up.mp3" loop="loop"></audio>
<audio id="up" src="./res/up.mp3" loop="loop"></audio>
hi I've just began studying html&js, and the code above worked fine on IE, but only the alert happened on chrome. Is this normal?
3 Answers
3
This is because chrome throws an exception :
DOMException: The element has no supported sources.
"code": 9,
"name": "NotSupportedError",
"message": "The element has no supported sources."
Chrome has changed it's policy because blocking roughly half of unwanted media autoplays
blocking roughly half of unwanted media autoplays
READ : https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
Reference :
The Autoplay Policy launched in M66 Stable for audio and video
elements and is effectively blocking roughly half of unwanted media
autoplays in Chrome. For the Web Audio API, the autoplay policy will
launch in M70. This affects web games, some WebRTC applications, and
other web pages using audio features. Developers will need to update
their code to take advantage of the policy. More details can be found
in the Web Audio API section below.
Chrome's autoplay policies are simple:
I have edited your code to display the error
window.onload = function() {
const playPromise = document.getElementById("up").play();
// In browsers that don’t yet support this functionality,
// playPromise won’t be defined.
if (playPromise !== undefined) {
playPromise.then(function() {
// Automatic playback started!
}).catch(function(error) {
console.log(error);
// Automatic playback failed.
// Show a UI element to let the user manually start playback.
});
}
alert("k");
}
<audio id="up" src="http://hcmaslov.d-real.sci-nnov.ru/public/mp3/Queen/Queen%20'Back%20Chat'.mp3" loop="loop"></audio>
This is a result of Chrome's autoplay policy, which restricts sites from playing audio before the user has interacted with the page.
In summary autoplay in Chrome is Not allowed by default since april 2018. This to protect the user for undesired sounds. More info.
But, if the user interacts with the page (by making a click for example), then yes it is allowed, so you can change the onload code to a click. Like this:
window.addEventListener("click", function(event) {
document.getElementById("up").play();
alert("k");
});
Click on the page, and walla.
Hope it helps.
I'll try this out, thank you^^
– H.Matthew
Jun 30 at 1:15
you're welcome, Have you tried?, do you need any more help?
– Marcelo Rossi
17 hours ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
wow, thank you so much
– H.Matthew
Jun 30 at 1:14