Unable to use shortcuts like Cmd+A, Cmd+C, Cmd+V inside an iframe inside a webview on macOS
Edit: This is unrelated to clipboard operations, because Cmd+A doesn't work either.
I created a simple repro here that opens an iframe inside a webview:
https://github.com/DanTup/vs-code-webview-copy-paste
The webview contains a text input. You cannot copy, paste, or even Select All inside that text input.
(Original post below)
I'm embedding an app inside a webview using an iframe (avoiding the iframe is not likely feasible). In order to have VS Code keyboard shortcuts still work, keypresses are passed over using the code here:
- https://github.com/microsoft/vscode/issues/65452#issuecomment-586036474
- https://github.com/microsoft/vscode/issues/65452#issuecomment-586485815
This works for many keypress (for example opening the command palette), however it's not possible to use Cmd+C to copy to the clipboard. Edit -> Copy works as expected.
It's not clear if there needs to be some extra handling in the webiew or iframe to make this work, or if it needs support from VS Code.
To reproduce:
- check out the webview sample from https://github.com/microsoft/vscode-extension-samples/tree/main/webview-sample
- remove the CSP header and add an iframe that has code to pass keypresses up to the webview and to dispatch the event:
<iframe src="https://blog.dantup.com/testing/vscode_iframe.htm" style="width: 600px; height: 600px;"></iframe> <script> window.addEventListener("message", (e) => { window.dispatchEvent(new KeyboardEvent('keydown', JSON.parse(e.data))); }, false); </script>
Run the extension and use the command to open the webview. Confirm Cmd+Shift+P opens the command palette even when focus is in the webview. Highlight some text and press Cmd+C, and note that the selected text was not copied to the clipboard.
We can access navigator.clipboard on webview:
https://github.com/microsoft/vscode/blob/0e522752712dbf744f2fb9e783e4386181945b0d/src/vs/workbench/contrib/webview/browser/webviewElement.ts#L375
Instead of calling window.dispatchEvent, we can call window.navigator.clipboard.writeText. We also have to send a text to copy from the child iframe.
Interestingly, we cannot access navigator.clipboard inside the child iframe in the webview even if we add allow="clipboard-read; clipboard-write;" to the iframe tag in the parent webview. This might be related to the following issue:
- https://bugs.chromium.org/p/chromium/issues/detail?id=1074489
@DanTup I'm also working on a similar problem, but the problem is a little more complicated than I thought, is there any progress on your side?
Unfortunately not, I wasn't able to make this work at all. I also couldn't determine whether it was a VS Code, Electron or Chrome issue 😞
I was hoping someone here might understand the issue better than I did :-)
I feel like it's an issue with iframes, it's hard to get events from inside it, I'll continue to look into it, but it feels hard to get result TAT
I feel like it's an issue with iframes, it's hard to get events from inside it,
It seems to be specific to VS Code though. If I create a bunch of nested frames across origins in the same way in a web page it all works fine. I just haven't figured out what's different about VS Code.
any update on this?
still not working...
still not able to copy
I am facing this same issue. I added a listener to log to the console when the Clipboard copy event occurs in both the parent webview and the child iframe. i.e:
//add this to the webview
window.addEventListener("copy", (e) => { console.log(`[parent] copy triggered`) });
//add this to the iframe
window.addEventListener("copy", (e) => { console.log(`[child] copy triggered`) });
When you use the menu Edit > Copy the event is triggered in the iframe. This is correct behavior. When you use CTRL+C or CMD+C keyboard shortcuts, the copy command is triggered on the webview, not on the iframe.
I think this happens because during the iframes keydown events, the focus is not on the iframe, but on the webview. I think this issue could be related to https://github.com/microsoft/vscode/issues/64729.
So, my current solution is to capture the keydown events in the child iframe, check if its a clipboard shortcut, and execute the correct command, i.e:
function handleKeyDown(
/**
* @type {KeyboardEvent}
*/
event
) {
if ((event.ctrlKey || event.metaKey) && event.code === "KeyC") {
document.execCommand("copy");
} else if ((event.ctrlKey || event.metaKey) && event.code === "KeyX") {
document.execCommand("cut");
} else if ((event.ctrlKey || event.metaKey) && event.code === "KeyV") {
document.execCommand("paste");
}
}
After the above check, I also still propagate the keydown event to its parent using postMessage otherwise other keyboard shortcuts on VSCode would not work.
function handleKeyDown( /** * @type {KeyboardEvent} */ event ) {
if ((event.ctrlKey || event.metaKey) && event.code === "KeyC") { document.execCommand("copy"); } else if ((event.ctrlKey || event.metaKey) && event.code === "KeyX") { document.execCommand("cut"); } else if ((event.ctrlKey || event.metaKey) && event.code === "KeyV") { document.execCommand("paste"); }}
Thank you for this workaround. I had been trying to solve this for days and I could barely find any info on it. Looks like a commit was merged to fix it, as well.
So what is the root cause? It looks like the nested iframe can't get keydown events from the vscode webview 🤔
@TheKenS that's correct. Here's a minimal example of a workaround I am using: https://gist.github.com/prmichaelsen/f6233f9ff0347cc04234316c24d501ea
This fixes Ctrl + C etc but does not fix the issue with right clicking.
It basically just sends keystrokes back and forth between VSCode, the webview, and the internal iFrame
Any update on a vscode side solution for this?
Not being able to copy is one of the bigger issue with the customer satisfaction for our extension.
I did some more testing of this and it appears to be unrelated to clipboard operations, because Cmd+A doesn't work either.
I created a simple repro here that opens an iframe inside a webview:
https://github.com/DanTup/vs-code-webview-copy-paste
The webview contains a text input. You cannot copy, paste, or even Select All inside that text input.
As far as I can tell, it's only a macOS issue (I cannot test Linux, but Windows is fine for Ctrl+A, Ctrl+C, Ctrl+V).
Edit: This is unrelated to clipboard operations, because Cmd+A doesn't work either.编辑:这与剪贴板操作无关,因为 Cmd+A 也不起作用。
I created a simple repro here that opens an iframe inside a webview:我在这里创建了一个简单的重现,在 web 视图中打开一个 iframe:
https://github.sheincorp.cn/DanTup/vs-code-webview-copy-paste
The webview contains a text input. You cannot copy, paste, or even Select All inside that text input.Web 视图包含文本输入。您无法在该文本输入中复制、粘贴甚至全选。
(Original post below) (以下为原帖)
I'm embedding an app inside a webview using an iframe (avoiding the iframe is not likely feasible). In order to have VS Code keyboard shortcuts still work, keypresses are passed over using the code here:我使用 iframe 将应用程序嵌入到 webview 中(避免 iframe 不太可行)。为了让 VS Code 键盘快捷键仍然有效,请使用此处的代码传递按键:
- macOS: some commands no longer work inside iframe inside webview #65452 (comment)macOS:某些命令不再在 webview 内的 iframe 中工作#65452(评论)
- macOS: some commands no longer work inside iframe inside webview #65452 (comment)macOS:某些命令不再在 webview 内的 iframe 中工作#65452(评论)
This works for many keypress (for example opening the command palette), however it's not possible to use Cmd+C to copy to the clipboard. Edit -> Copy works as expected.这适用于许多按键(例如打开命令选项板),但无法使用 Cmd+C 复制到剪贴板。编辑 -> 复制按预期工作。
It's not clear if there needs to be some extra handling in the webiew or iframe to make this work, or if it needs support from VS Code.目前尚不清楚是否需要在 webiew 或 iframe 中进行一些额外的处理才能实现此功能,或者是否需要 VS Code 的支持。
you can try this code in your iframe
document.addEventListener('keydown', function (event) {
if ((event.metaKey || event.ctrlKey) && event.key === 'v') {
document.execCommand('paste');
}
});
@qiyx2019 did this work for you? In my testing, those key events never fired (and the issue is not just handling Ctrl+V, it's other combinations like Ctrl+A and Ctrl+C).
any update on this fix ?
I updated my repo at https://github.com/DanTup/vs-code-webview-copy-paste to log all keypresses and copy/paste events. On Windows, I see what I'd expect - keydown/keyup for Ctrl and A/C/V, and the copy/paste events fire:
However on macOS, the up event never occurs for the A/C/V key, and the copy/paste events never fire. I wonder if the missing keyUp is the underlying issue, and if that was fixed the native Copy/Paste behaviour would work too?
I don't know where to start debugging this in VS Code though.
I did some more poking around and found that in the top-level webviews, VS Code is intercepting these keypresses and calling preventDefault() and instead passing them up to VS Code:
https://github.com/microsoft/vscode/blob/3add072f87d142a8de947b8376de2c805bd2a6fe/src/vs/workbench/contrib/webview/browser/pre/index.html#L623-L630
I think this is so other VS Code shortcuts can work when a webview had focus. If you happen to trigger copy/paste etc., then VS Code passes the command back down using execCommand.
On Windows, the browser/OS still handles Ctrl+C etc., so things work inside the iframe, but on macOS VS Code calls setIgnoreMenuShortcuts(true) which prevents this behaviour, which is why they don't work.
Despite my (Claude's) best efforts, I couldn't find a way to update VS Code to automatically handle this for nested frames (because the nested frame is another origin, it can't reach in and handle keypresses), however I did find that within the iframe I can capture the keypresses in the same was VS Code does, but rather than forward them upwards I can just call execCommand. Apparently execCommand is deprecated, but it's working and VS Code is also still using it, so probably it's fine for now.
So dropping this script inside your nested iframe should solve the issue. Unfortunately it makes assumptions about which shortcuts should perform which actions (I'm not sure if VS Code lets you rebind these, but if it does, that won't work here - but I'm also not sure that will work in the top-level webview either) and might not handle everything (redo?), but feel free to tweak.
function handleInnerKeydown(e) {
const hasMeta = e.ctrlKey || e.metaKey;
const code = e.keyCode;
if (hasMeta && code === 86 || e.shiftKey && code === 45) {
// Ctrl+V or Shift+Insert
document.execCommand("paste");
} else if (hasMeta && code === 67) {
// Ctrl+C
document.execCommand("copy");
} else if (hasMeta && code === 88) {
// Ctrl+X
document.execCommand("cut");
} else if (hasMeta && code === 65) {
// Ctrl+A
document.execCommand("selectAll");
// Ctrl+X
} else if (hasMeta && code === 90) {
document.execCommand("undo");
} else {
return;
}
// If we didn't return above, we triggered a command and want to suppress
// browser handling.
e.preventDefault();
}
window.addEventListener('keydown', handleInnerKeydown);
@mjbvz if you happen to have any ideas about how this could be done in VS Code before we start putting this workaround everywhere (or a way to inject this automatically into the nested iframe so it doesn't need doing by the inner app), I'm all ears :-)
Edit: I forgot to dump these related commits/issues I found while looking into this, in case they're useful:
- https://github.com/microsoft/vscode/issues/101946
- https://github.com/microsoft/vscode/pull/101958
- https://github.com/microsoft/vscode/issues/106383
- https://github.com/microsoft/vscode/commit/e13875b77c89b95f20ccb5667e14ff164c198e57
- https://github.com/microsoft/vscode/commit/9cdf2501232c60881d8da7e9084d1e963cedc62e