对iframe或frameset框架内部元素操作办法

带有iframe或frameset框架的情况下,如何对内部元素进行操作,要先找到这个框架,再其基础上进行操作,代码如下:

  1. var frame = document.querySelector("body > frameset");
  2. //var frame = document.querySelector("#myFrameset");
  3. var options = frame.childNodes[1].contentWindow.document.querySelectorAll("select");
  4. for(let i=0;i<options.length; i++){
  5. let n = Math.floor(Math.random() * 3) + 1;
  6.     options[i].children[n].selected=true;
  7. }
  8. frame.childNodes[1].contentWindow.document.querySelectorAll("input")[1].click();
bash

解释:

找到此框架,如果框架内部有多个子框架,需要选择其子框架,然后借用contentWindow过渡一下,然后就是正常的document了。