【问题标题】:Need to disable Javascript within an iFrame需要在 iFrame 中禁用 Javascript
【发布时间】:2016-03-16 21:09:41
【问题描述】:

我正在建立一个投资组合网站;它是具有灯箱功能的单页寻呼机。所以,基本上我展示的是我制作的 HTML5 广告,我将其嵌入到 iFrame 中。这些广告有音频,所以当我关闭灯箱时,音频会继续播放。现在我尝试了不同的方法,但都没有成功。我已经测试了一种有效的方法,其中我删除了 iFrame 的 src(我分配了一个 ID 的一个 iFrame)。像这样:

**HTML:**
<iframe id="test" class="iframe-src" src="media/rogue-nation/300x250-progressive-post/index.html" width="300" height="250" style="border:none"></iframe>

**JavaScript:**
var test;
var lightbox;

test = document.getElementById('test');
lightbox = document.getElementById('lightbox');

lightbox.addEventListener("click", closeLightbox, false);

function closeLightbox() {
...
test.src = "none";
}

所以...我的问题是:

  • 根据与哪个 iFrame 交互,将此方法应用于每个 iFrame 的“最佳”方式是什么(尝试过 getElementsByClassName 但不成功)
  • 有没有一种方法可以禁用 iFrame 中的脚本,所以我不必使用这种方法,因为我对此并不那么着迷
  • 另外,请不要发布 jQuery 解决方案或建议我使用 jQuery,因为我正在编写纯 JavaScript,这不会有帮助

提前致谢!

【问题讨论】:

  • 您是否在同一个域中托管您的灯箱中的内容? (看起来像你使用“media/...”作为 iframe src)
  • 是的,我正在将在目录中组织的 HTML5 广告加载到这些 iFrame 中。 (我正在加载 index.html)

标签: javascript html iframe web


【解决方案1】:

如果您的 iframe 内容位于同一个域中,这很容易。当您的灯箱关闭时,您可以执行以下操作:

function closeLightbox() {
    // get the iframe which is playing audio
    var iframe = document.getElementById('iframe');
    // make sure you can reference the audio element on the iframe
    // e.g. with an id.
    var sound = iframe.contentWindow.document.getElementById('sound');
    sound.pause();
    sound.currentTime = 0;
    // then close the lightbox with some other code
    // ...
}

JSBin Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2017-07-11
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多