Javascript iframe src 仅在开始时变为 Null

Javascript iframe src becomes Null at start only

我的 iframe src 有点问题。我设置了一个下拉列表,它更改了 iframe src url,然后保存选择。一切正常,除非您第一次加载网页时出现 404 错误并且 iframe src 变为空。我尝试手动设置 url 并使用脚本更改 url onload 但这破坏了保存选择。谢谢你的时间。

编辑 多亏了 lorefnon,他为我指出了正确的方向,我才能够创建一个修复程序,这里是完整的工作代码。

<html>
<head>
<title>dropdown remember selection test</title>
</head>
<body>

<iframe id="stream_iframe" marginwidth="0" marginheight="0" width="854"   height="480" scrolling="no" allowtransparency="true" frameborder="0" framespacing="0" name="stream_iframe" src="http://vaughnlive.tv/embed/video/moviebay"></iframe> 

<form>
<select name="options" onchange="callMe(this);" id="selectMovie">
<option value="" disabled selected>SELECT STREAM</option>
<option value="http://vaughnlive.tv/embed/video/ninjatart">Nightsanity</option>
<option value="http://vaughnlive.tv/embed/video/111aaacharkcomedy">ComedyCentral</option>
<option value="http://vaughnlive.tv/embed/video/ducktoaster">JPGameShow</option>
<option value="http://vaughnlive.tv/embed/video/lmshows_mws">SurvivalReality</option> 
<option value="http://vaughnlive.tv/embed/video/cyberjedi">TV Series</option>
<option value="http://vaughnlive.tv/embed/video/anime_hq">Anime HQ</option>
<option value="http://vaughnlive.tv/embed/video/animationnation101">Toons</option>
<option value="http://vaughnlive.tv/embed/video/frightfest0001">Horror Movies 1</option> 
<option value="http://vaughnlive.tv/embed/video/freakyfetish101">Horror Movies 2</option>
<option value="http://vaughnlive.tv/embed/video/moviebay">MovieBay</option>
<option value="http://vaughnlive.tv//embed/video/111aaacharkmovies">Movies</option> 
</select>
</form>
<script>
function callMe(obj){
localStorage.setItem("selectedStream",obj.options[obj.selectedIndex].value);
document.getElementById('stream_iframe').src =       obj.options[obj.selectedIndex].value;
}

var selectedStream = localStorage.getItem("selectedStream");

if (localStorage.getItem("selectedStream") === null) {
  document.getElementById("stream_iframe").src =  "https://streamup.com/acgn_music_box/embeds/video?startMuted=false"; 
} else {
    document.getElementById("stream_iframe").src =   localStorage.getItem("selectedStream");
    document.getElementById("selectMovie").value =  ""+localStorage.getItem("selectedStream")+"";
}
</script>
</body>
</html>

问题是当您的代码第一次运行时,localStorage.getItem returns null 分配给您的 iframe 的 src 属性。

您可以检查这种情况,或者什么都不做,在这种情况下,html 中现有的 src 将被尊重,或者您可以分配 'about:blank' 以显示没有 404 错误的空页面.

<script>
function callMe(obj){
localStorage.setItem("selectedStream",obj.options[obj.selectedIndex].value);
document.getElementById('stream_iframe').src =   obj.options[obj.selectedIndex].value;
}

var selectedStream = localStorage.getItem("selectedStream");

if (selectedStream) {
  document.getElementById("stream_iframe").src = selectedStream;
  document.getElementById("selectMovie").value = selectedStream;
} else {
  document.getElementById("stream_iframe").src =  "about:blank"; 
}

</script>