项目场景:

electron项目的webview需要注入preload js,但是我发现注入的preload js似乎没有正常执行。随即想打开webview网页的devtools看看。代码如下


问题描述:

如下代码在运行后devtools会闪一下,随即消失。

index.html

<webview id="link-view" src="https://v.qq.com/x/page/m3206njx773.html" allowpopups preload="js/inject.js"
       nodeintegration disablewebsecurity plugins class="webview"></webview>
<script type="text/javascript">
  const webview = document.getElementById('link-view')
    webview.addEventListener("dom-ready", function () {
      webview.openDevTools({ mode: 'bottom' });
    });
</script>

main.js

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {

      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: true,
      // 使用webview
      webviewTag: true,
      // // 取消跨域限制
      // webSecurity: false,
      // // 支持多线程
      nodeIntegrationInWorker: true,
      // 
      nodeIntegrationInSubFrames: true,
      // plugins: true,
      // allowDisplayingInsecureContent: true
    }
  })
  // win.openDevTools()
  win.loadURL('file://' + __dirname + '/ui/index.html');
}

原因分析:

最终经过调试js代码修改如下,可成功打开的devtools。webview的devtools只能单独打开,不能指定它打开的位置


解决方案:

<script type="text/javascript">
  const webview = document.getElementById('link-view')
    webview.addEventListener("dom-ready", function () {
      webview.openDevTools();
    });
</script>
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐