我希望网页通过连接到服务器来定期检查某些情况。 如果出现这种情况,应该发布通知,并播放声音。
为了播放声音,必须有一些用户交互,所以我问用户 单击页面以使整个过程顺利进行,我称之为启动。
为了反复检查情况,我需要刷新页面。 但这需要用户再次单击(重复),所以我使用 iframe 并刷新它。 而且它有效。
但是......在 Firefox 中(显然,只是),如果我刷新父页面本身 (无论出于何种原因),然后 Firefox 会“有帮助地”自动重新加载 iframe, 并立即 launch 。 然后声音就不会播放了。
我希望避免必须记住要做的事情 在父页面上进行硬刷新,或者在进行软刷新后记得单击 刷新了一下,没找到。 Chrome 浏览器不这样做,但我更喜欢 使用火狐浏览器。
这是我尝试过的方法,但不起作用。
<script>
var launched = false;
function launch()
{
console.log("Launching: launched = " + launched);
if (!launched)
{
document.getElementById("framex").src = "checkalive1.shtml";
launched = true;
}
}
function virginstate()
{
console.log("virginstate called with launched = " + launched);
document.getElementById("framex").src = "";
launched = false;
}
</script>
<body onload="virginstate()" onclick="launch()">
<iframe id="framex" src=""> </iframe>
</body>
在浏览器控制台中:
virginstate called with launched = false
Autoplay is only allowed when approved by the user,
the site is activated by the user, or media is muted.
checkalive1.shtml:168:7 Uncaught (in promise) DOMException:
The play method is not allowed by the user agent or the platform
in the current context, possibly because the user denied permission.
我自己找到了答案,或者我应该说,an答案。 答案是:通过 javascript 在页面加载之后(或接近结束时)添加 iframe。 参考:
Javascript:页面加载后添加 iframe 元素- 谢谢 Stackoverflow 社区。 具体来说,而不是
<iframe src=somepage.html>
我用
const iframe = document.createElement("iframe");
iframe.id = "framex";
document.getElementById("whereIwantThe").appendChild(iframe);
这会阻止 Firefox 预加载 iframe 的 html,直到我稍后要求它提供源文件。