插入一个div和脚本到一个页面上的iframe
问题描述:
我有一个页面上有一个iframe,我正在使用jQuery试图添加一个额外的脚本到iframe和一个空的div在最后。插入一个div和脚本到一个页面上的iframe
的iframe代码:
<iframe class="kaltura" style="width: 608px; height: 402px;" title="EPI-522_Orav_Survival_Review_Part 1_Study Elements-H264 MP4 2Mbit 16x9 [22:17]" src="/courses/2873/external_tools/retrieve?borderless=1&url=https://hsphprod.kaf.kaltura.com/browseandembed/index/media/entryid/1_rs4bvlrn/showDescription/false/showTitle/false/showTags/false/showDuration/false/showOwner/false/showUploadDate/false/playerSize/608x402/playerSkin/30101351/" width="300" height="150" allowfullscreen="allowfullscreen" webkitallowfullscreen="webkitallowfullscreen" mozallowfullscreen="mozallowfullscreen"></iframe>
到目前为止,脚本我有是:
jQuery(document).ready(function ($) {
// for each of the kaltura iframes
$('.kaltura').each(function (index) {
// find the body and add these items after
$(this).contents().find('body').append('<div id="threeplay-div"></div>');
// create the script element and insert it into the page
$(this).contents().find('#threeplay-div').append($("<script />", {
type: "text/javascript",
async: true,
src: "//static.3playmedia.com/p/projects/11439/files/831301/plugins/10616.js"
}));
});
});
,但运行时它不检测I帧,也没有追加股利或脚本到它。任何人有一个想法如何得到这个工作?
答
您的iframe内容可能尚未加载到document.ready上。您应该在iframe加载时附加回调。像这样$(iframe).on('load',callback);
如果iframe src与您的域名不同,那么您无法从您的代码访问iframe内容。这就是浏览器向外部加载的文档提供的安全性。
答
您提供不附加内iframe
div
和script
样品,而是附加在只在当前窗口的div
。示例代码(如下所示)在iframe
内附加script
标记,jquery用于创建script
标记。
jQuery(document).ready(function ($) {
// for each of the kaltura iframes
$('iframe.class').each(function (index) {
// find the body and add these items after
$(this).contents().find('body').append('<div id="inserted-div"></div>');
// create the script element and insert it into the page
$(this).contents().find('#inserted-div').append($("<script />", {
type: "text/javascript",
//src : src,
async: true,
src: "//www.example.com/javascript.js"
}));
});
});
试试这个jsfiddle例子,用f12
(开发人员工具)来验证。
使用下面的代码如何做到这一点的任何recomendation? – dpegasusm