使用 Observer 检测 iframe 中的 innerHTML 更改

问题描述

我正在为 Chrome 创建一个扩展程序,我需要检测 innerHTMLiFrame 内的变化。

我举了两个例子:

  • 这很有效(在 iFrame 之外):

// select the target node
var target = document.querySelector('#contador');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  console.log($('#contador').text());   
});
// configuration of the observer:
var config = { attributes: true,childList: true,characterData: true };
// pass in the target node,as well as the observer options
observer.observe(target,config);
<div id="contador"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<!-- Script for random number with 3 seconds interval -->
<script>
var myInterval = setInterval( function (){
  
var num = parseInt( Math.random()*100 )+1; 
  
  $('#contador').html( num ) ; 
  
},3000);
</script>

  • 它不起作用(在 iFrame 内): (它返回:Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not type 'Node'. in JSFiddle

var iframe = window.frames[0];

// select the target node
var target = iframe.document.querySelector('#contador');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  console.log($('#contador').text());   
});
// configuration of the observer:
var config = { attributes: true,config);
<!-- iframe with script for random number hosted in 000webhost-->

<iframe src="https://ipaymobile.000webhostapp.com">
</iframe>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

我做错了什么?

注意:我访问的页面是这样的:

https://xxxxx.service-now.com/nav_to.do?uri=%2F$pa_dashboard.do

这是 iframe html:

<iframe id="gsft_main" allowfullscreen="true" main-pane="true" name="gsft_main" title="Fila de Atendimento | ServiceNow" aria-label="Conteúdo principal" src="$pa_dashboard.do" data-original-title="Conteúdo principal"></iframe>

如果我单击 iframe src 并在新选项卡中打开它,请打开此链接

https://xxxxx.service-now.com/$pa_dashboard.do

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)