无星的electron之旅(十五)—— electron访问iframe

1,096 阅读1分钟

一、背景

一个偶然的情况,帮一个朋友写个小工具

需要内嵌用到iframe,并使用document提取其中的一些dom元素

二、报错

好像是这个,记不清楚了=。=

Blocked a frame with origin "***" form accessing a cross-origin frame.

三、解决

入口添加

app.commandLine.appendSwitch('disable-site-isolation-trials');


// ***
new BrowserWindow({
    // ***
    webPreferences: {
        // ***
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false,
      allowRunningInsecureContent: true
    },
  })

四、正常拿dom


const Iframe = ref<HTMLIFrameElement | null>(null);

const iframeLoad = () => {
    // 业务脱敏
    Iframe.value = document.querySelector("iframe")
    // 非IE
    Iframe.value!.onload = () => {
        // 获取document
        let iframeDom: HTMLIFrameElement = document.getElementById('Iframe') as HTMLIFrameElement
        let doc = iframeDom.contentDocument
        const time = doc?.querySelector("xpath")
    };
}
onMounted(() => {
    iframeLoad()
})

done