Added a custom title bar to a frameless window in order to make the window draggable. The title bar shows, but eventListener won’t fire:
main.js:
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
frame: false,
scrollbar: false,
webPreferences:{
nodeIntegration: true,
contextIsolation: false,
}
})
win.loadFile('index.html')
}
index.html:
<body>
<div class="window">
<div class="window-content">
<textarea>some content</textarea>
</div>
</div>
<script src="index.js"></script>
</body>
index.js:
let titleBar = document.createElement('div')
titleBar.style.width = "100%"
titleBar.style.height = "32px"
titleBar.style.backgroundColor = "#fff"
titleBar.style.position = "absolute"
titleBar.style.top = titleBar.style.left = 0
titleBar.style.webkitAppRegion = "drag"
titleBar.textContent = 'My App';
document.body.appendChild(titleBar)
// Nothing happens
titleBar.addEventListener("mouseover", () => {
console.log("hello")
})
2
Answers
You don’t need to use eventListener, you can achieve this use only CSS.
main.js
index.html
index.css
Yes, it is possible to add an eventListener to a custom title bar in a frameless window.
The issue you are observing is caused by
which interferes with the mechanism of propagating the events and prevents the mouse events to be detected by the listener.
In other words it seems that in Electron you can’t have both at the same time: the dragging and the firing of the mouse events.
To see it yourself comment or remove the "drag" line and experience that the mouse event is then working as expected ( don’t forget that the console output is provided after Ctrl+Shift+i in the window of the application and not in the Terminal window running the application ).
A possible workaround is to have two title bars: one for dragging the window and the other one for responding to mouse events:
Here how it looks like: