Skip to content

Instantly share code, notes, and snippets.

@BurningEnlightenment
Created December 13, 2023 11:02
Show Gist options
  • Save BurningEnlightenment/83ef1268fa71ebe0fafd9dfa4cc2811f to your computer and use it in GitHub Desktop.
Save BurningEnlightenment/83ef1268fa71ebe0fafd9dfa4cc2811f to your computer and use it in GitHub Desktop.
electron form submission fetch-forward failure
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; connect-src http://127.0.0.1:3000">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<p>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
</p>
<p>
Koa responded: <span id="koa-response"></span>
</p>
<form action="http://127.0.0.1:3000/" method="post">
<input required id="txt1" name="txt1" value="" type="text" autofocus>
<button name="submit" type="submit">submit</button>
</form>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>
import Koa from 'koa';
const app = new Koa()
app.use(async ctx => {
ctx.body = 'Hello World'
})
app.listen(3000, '127.0.0.1')
import { app, BrowserWindow, net, session } from 'electron'
import * as path from 'node:path'
import * as url from 'node:url';
import { Worker } from 'node:worker_threads';
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
// enabling any of these flags allows the form submission to succeed
const ENABLE_WORKAROUND = false;
const DISABLE_HTTP_HANDLER = false;
// the follewing flags currently don't seem to influence the erroneous behaviour
const USE_PERSISTENT_SESSION = false;
function createWindow () {
const wsession = session.fromPartition(`${USE_PERSISTENT_SESSION ? 'persist:' : ''}xname`)
wsession.protocol.handle('http', async (request) => {
if (ENABLE_WORKAROUND && request.headers.get('origin') === 'null') {
request.headers.delete('origin')
}
try {
return await wsession.fetch(request, { bypassCustomProtocolHandlers: true, })
} catch (error) {
console.warn(
`${request.method} ${request.url} faild unexpectedly. `
)
throw error
}
})
if (DISABLE_HTTP_HANDLER) {
wsession.protocol.unhandle('http')
}
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
session: wsession
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
const worker = new Worker(path.join(__dirname, "koa.mjs"))
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
app.on('will-quit', function () {
worker.terminate();
})
{
"name": "fetch-failure",
"productName": "fetch-failure",
"description": "My Electron application description",
"keywords": [],
"main": "./main.mjs",
"version": "1.0.0",
"author": "gassmann",
"scripts": {
"start": "electron ."
},
"dependencies": {
"koa": "2.14.2"
},
"devDependencies": {
"electron": "28.0.0"
}
}
/**
* The preload script runs before. It has access to web APIs
* as well as Electron's renderer process modules and some
* polyfilled Node.js functions.
*
* https://www.electronjs.org/docs/latest/tutorial/sandbox
*/
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
/**
* This file is loaded via the <script> tag in the index.html file and will
* be executed in the renderer process for that window. No Node.js APIs are
* available in this process because `nodeIntegration` is turned off and
* `contextIsolation` is turned on. Use the contextBridge API in `preload.js`
* to expose Node.js functionality from the main process.
*/
fetch('http://127.0.0.1:3000/',
{
method: 'POST',
body: "param=value",
headers: {
'content-type': 'application/x-www-form-urlencoded',
'origin': 'null'
},
window: null
})
.then(async (response) => {
const element = document.getElementById("koa-response")
if (element) element.innerText = await response.text()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment