【问题标题】:Playing audio via an iframe using javascript使用 javascript 通过 iframe 播放音频
【发布时间】:2013-04-14 15:15:23
【问题描述】:

我在abc.jsp中有以下代码

 <% 
 out.write("<script type=\"text/javascript\" src=\"scripts/test.js\"></script>");
 out.write("Here is filename"+sfl);
 out.write(""
        + "<input type=\"button\" id=\"playBt\" value=\"Play Now\" onClick=\"playSound()\" >"
        + "<audio id=\"sound\" preload=\"auto\">"
        + "<source src=\"music.ogg\" type=\"audio/ogg\" />"
        + "<source src=\"music.mp3\" type=\"audio/mpeg\" />"
        + "Your browser does not support the audio element."
        + "</audio>"
      );
out.write("");
%>

然后上面的内容被引入到index.jsp的一个框架中

 <iframe id='bgframe' style='display:compact;' src='abc.jsp' width="400" height="200"></iframe>

现在使用这个 JavaScript 函数 - test.js

function playSound() {  
  var frameRef = document.getElementById('bgframe');
  var sound = frameRef.contentWindow.document.getElementById'sound');
  //var sound = frameRef.contentDocument.document.getElementById('sound');
  sound.play();
}

问题是,当我点击播放按钮时,声音没有播放。 在 JavaScript 控制台上,系统返回 null 作为值 frameRef。 此外,根据我使用的是contentDocument 还是contentWindow,我会收到以下错误。

Uncaught TypeError: Cannot read property 'contentDocument'
Uncaught TypeError: Cannot read property 'contentWindow'

我已经实现了不同的解决方案,但未捕获的 typedef 错误仍然存​​在。

请问我在这里做错了什么,我该如何解决?为什么我无法访问框架id=bgframe 上的元素?

【问题讨论】:

    标签: javascript iframe frame


    【解决方案1】:

    您将test.js 包含在abc.jsp 中,not 包含在index.jsp 中,因此您无需引用 iframe,因为脚本已经在其中运行。 你只需要在playSound()函数中做一些改动:

    function playSound() {  
      var sound = document.getElementById('sound');
      //do your stuff here
      //line below should make your script alert 'auto' in your case
      alert(sound.preload); 
    }
    

    【讨论】:

    • test.js 是一个外部 javascript。它不包含在 abc.jsp 中。另外,我打算做的是能够通过一个框架在 index.jsp 上播放这个声音。当我在没有框架的情况下对其进行测试时,一切正常,但我需要通过嵌入在 index.jsp 中的框架来播放它。
    • 错误专门指向这一行:var sound = frameRef.contentWindow.document.getElementById'sound');返回 null 的地方。
    • 您将 test.js 包含在 abc.jsp out.write("&lt;script type=\"text/javascript\" src=\"scripts/test.js\"&gt;&lt;/script&gt;"); 的第二行中。您的 test.js 在 iframe(在 abc.js 中)中运行,而不是直接在 index.jsp 中。我认为你不明白你在做什么 :) 首先检查我的代码是否适合你。
    • 感谢您的反馈。你在这里看到的是一段我试图在一个更大的项目中实现的代码。您看到我通过 iframe 在 index.jsp 中调用 abc.jsp 的原因是,归根结底,我的代码可能在不同的域上运行,但我只会将 iframe 代码行提供给客户端放在他们的网站上。这样,我让我的 test.js 包含在 abc.jsp 中,这样只有一行代码同时加载了我的 javascript 和 jsp。我不想给客户多行代码。我刚刚找到了解决方案。
    • 这个链接 (stackoverflow.com/questions/5371047/…) 给了我一些见解。在那里我发现我在 DOM 完全加载之前调用了 playSound() 。现在,在我将代码放入 window.onload = function(){... 后它就可以工作了
    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    相关资源
    最近更新 更多