简体   繁体   中英

React + Electron webview tag preload js not working

When I use webview tag, preload js not working

my code is as follows:

// test.js
<div>
    <webview id="foo" src="https://www.github.com/" preload="file://preload.js"/>
</div>

my preload.js file:

// preload.js
alert('preload success')

I also tried this:

// test.js
<div>
    <webview id="foo" src="https://www.github.com/" preload={`file://${__dirname}/preload.js`}/>
</div>

and I even intercepted the file protocol in main.js

// main.js
app.on('ready', () => {
  protocol.interceptFileProtocol('file', (request, callback) => {
    console.log('success')
    const url = request.url.substr(7);
    callback({path: path.normalize(`${__dirname}/${url}`)});
  }, (error) => {
    if (error) console.error('Failed to intercept protocol');
  });
})
;

But none of these attempts worked. There is no "success" in the console and no "success" alert. But if I use an absolute path like this:

// test.js
<div>
    <webview id="foo" src="https://www.github.com/" preload="file:///home/ppp/electron-dict/src/components/preload.js"/>
</div>

the code runs fine and my application alerts "success." Why is this?

my project path:

├── public
│   ├── index.html
│   ├── main.js
├── src
│   ├── App.js
│   ├── components
│   │   ├── test.js
│   │   ├── preload.js
│   └── index.js

Electron and React versions:

├─ electron@7.1.1
├─ react@16.11.0

Indicate preload is a top level attribute of the webview tag, not inside webpreferences

<webview src="https://www.github.com/" preload="./test.js"></webview>

A String that specifies a script that will be loaded before other scripts run in the guest page. The protocol of script's URL must be either file: or asar: , because it will be loaded by require in guest page under the hood.

When the guest page doesn't have node integration this script will still have access to all Node APIs, but global objects injected by Node will be deleted after this script has finished executing.

Note: This option will appear as preloadURL (not preload ) in the webPreferences specified to the will-attach-webview event.

You can find more info on Electron preload script for webview not working?

I have been able to preload js, but not using the preload attribute. Instead, I inject it from the main process:

app.on('web-contents-created', (_event, contents) => {
  contents.on('will-attach-webview', (_wawevent, webPreferences, _params) => {
    webPreferences.preloadURL = `file://${__dirname}/webview-preload.js`;
  });
});

Using React in the renderer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM