如何从动态生成的iframe中删除onload事件?

时间:2017-08-10 14:07:26

标签: javascript jquery asp.net iframe

<div class="voc_container content-container">
<div class="voc_content">
    <h3 class="heading-small">Tell us what you think of this page</h3>
    <span class="voc_content_open">Take a short survey to give us your feedback</span>
    <span class="voc_content_close js-hidden">Close</span>
    <div class="voc_content_survey js-hidden">
    <script id="ss-embed-380173">
    (function (d, w) { 
    var s, ss;
    ss = d.createElement('script');
    ss.type = 'text/javascript'; 
    ss.async = true; 
    ss.src = ('https:' == d.location.protocol ? 'https://' : 'http://') + 
'www.xxxxxx.co.uk/s/r/embed.aspx?i=341674&c=380173';
};
    s = d.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ss, 
s); })(document, window);</script></div>
</div>
</div>**strong text**

生成html为

<iframe id="ss-embed-frame-380173" 
src="https://www.xxxxxxx.co.uk/s/YEXFX/" frameborder="0" style="border: 
0px currentColor; border-image: none; width: 100%; height: 400px; padding-
bottom: 4px;" onload="window.scrollTo(0, document.getElementById('ss-embed-
frame-380173').offsetTop);">&lt;a 
href="https://www.xxxxxxx.co.uk/s/YEXFX/"&gt;Please take our 
survey&lt;/a&gt;</iframe>

我尝试使用createelement删除列表器

  ss.removeEventListener("onload","window.scrollTo(0, 
  document.getElementById('ss-embed-frame-380173').offsetTop);");
 ss.onload=function(){} 

从动态生成的事件中删除onload事件,但不删除它。

任何人都可以帮助我指导如何从动态生成的iframe元素中删除onload事件???

onload="window.scrollTo(0, document.getElementById('ss-embed-
frame-380173').offsetTop);

2 个答案:

答案 0 :(得分:0)

你可以使用jQuery。

<script type="text/javascript">
    $("#ss-embed-frame-380173").removeAttr("onload");
</script>

答案 1 :(得分:0)

您可以使用MutationObserver来观察附加到document的元素,如果.removeAttribute("onload")或其他选择器匹配,则调用元素id.disconnect()观察者实例

<!DOCTYPE html>
<html>
<head>
<script>
const config = {
  childList: true,
  subtree: true
};

const observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    mutation.addedNodes.forEach(function(node) {
      if (new RegExp("^ss-embed-frame").test(node.id)) {
        node.removeAttribute("onload");
        observer.disconnect();
        console.log(node.getAttribute("onload"), node.outerHTML);
      }
    })
  })
})

observer.observe(document.documentElement, config);
</script>
<script>
let iframe = `<iframe id="ss-embed-frame-380173" 
src="data:text/plain,abc" frameborder="0" style="border: 
0px currentColor; border-image: none; width: 100%; height: 400px; padding-
bottom: 4px;" onload="window.scrollTo(0, document.getElementById('ss-embed-
frame-380173').offsetTop);">&lt;a 
href="https://www.xxxxxxx.co.uk/s/YEXFX/"&gt;Please take our 
survey&lt;/a&gt;</iframe>`;

onload = function() {
  document.body.innerHTML += iframe
};
</script>
</head>
<body>
</body>
</html>