electron支持自定义协议,如下是我从electron文档中摘抄的一段:
1 2 3 4 5 6 7 8 9 10 11 12
| const {app, protocol} = require('electron') const path = require('path')
app.on('ready', () => { protocol.registerFileProtocol('atom', (request, callback) => { const url = request.url.substr(7) callback({path: path.normalize(`${__dirname}/${url}`)}) }, (error) => { if (error) console.error('Failed to register protocol') }) })
|
假设在项目根目录下有文件one.js,并且one.js中使用了localStorage:
1
| localStorage.setItem('key', 'value')
|
这时候,你发起一个请求:atom://one.js那么你将会得到以下报错:
1
| Uncaught (in promise) DOMException: Failed to read the 'localStorage.setItem(key, value);' property from 'Window': Access is denied for this document.
|
你也许觉得疑问,百度搜索出来都是这么写的呀,为什么我的就错了,接下来就是开始怀疑人生了。
其实在electron的文档中明确的说明:

如果你需要使用Web Storage Apis,那么请这样写:
1 2 3 4 5 6 7 8 9 10 11 12
| const {app, protocol} = require('electron') const path = require('path')
protocol.registerStandardSchemes(['atom']) app.on('ready', () => { protocol.registerFileProtocol('atom', (request, callback) => { const url = request.url.substr(7) callback({path: path.normalize(`${__dirname}/${url}`)}) }, (error) => { if (error) console.error('Failed to register protocol') }) })
|