Please create an on screen keyboard app using js.
- User
Please create an on screen keyboard app using js.
- Assistant
Here’s a simple self-contained “On-Screen Keyboard” demo in HTML/CSS/JS. Just copy the code below into an
.htmlfile and open it in your browser! 🖥️⌨️<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>On-Screen Keyboard</title> <style> body { font-family: sans-serif; display: flex; flex-direction: column; align-items: center; margin: 40px; } #input-area { width: 80%; max-width: 600px; font-size: 1.2rem; padding: 10px; margin-bottom: 20px; } #keyboard { display: grid; grid-template-columns: repeat(14, 1fr); grid-gap: 5px; max-width: 800px; } .key { padding: 15px 0; background: #eee; text-align: center; border-radius: 4px; cursor: pointer; user-select: none; transition: background 0.1s; } .key:active, .key.highlight { background: #ccc; } .wide { grid-column: span 2; } .extra-wide { grid-column: span 3; } </style> </head> <body> <h1>Virtual On-Screen Keyboard</h1> <textarea id="input-area" rows="4" placeholder="Click the keys below…"></textarea> <div id="keyboard"></div> <script> (function() { const layout = [ ['`','1','2','3','4','5','6','7','8','9','0','-','=','Backspace'], ['Tab','q','w','e','r','t','y','u','i','o','p','[',']','\\'], ['Caps','a','s','d','f','g','h','j','k','l',';','\'','Enter'], ['Shift','z','x','c','v','b','n','m',',','.','/','Shift'], ['Space'] ]; const keyboard = document.getElementById('keyboard'); const textarea = document.getElementById('input-area'); let isCaps = false; // Build keys layout.forEach(row => { row.forEach(keyLabel => { const key = document.createElement('div'); key.textContent = keyLabel; key.className = 'key'; // sizing if (keyLabel === 'Backspace') key.classList.add('wide'); if (keyLabel === 'Tab' || keyLabel === 'Caps' || keyLabel === 'Enter' ) key.classList.add('wide'); if (keyLabel === 'Shift') key.classList.add('extra-wide'); if (keyLabel === 'Space') key.classList.add('extra-wide'); keyboard.appendChild(key); // click handler key.addEventListener('click', () => handleKey(keyLabel)); }); }); function handleKey(label) { const start = textarea.selectionStart; const end = textarea.selectionEnd; let value = textarea.value; switch(label) { case 'Backspace': if (start > 0) { textarea.value = value.slice(0, start - 1) + value.slice(end); textarea.setSelectionRange(start - 1, start - 1); } break; case 'Tab': insertText('\t'); break; case 'Enter': insertText('\n'); break; case 'Space': insertText(' '); break; case 'Caps': isCaps = !isCaps; toggleCaps(); break; case 'Shift': isCaps = true; toggleCaps(); // release shift after a keypress setTimeout(() => { isCaps = false; toggleCaps(); }, 300); break; default: const char = isCaps ? label.toUpperCase() : label.toLowerCase(); insertText(char); } textarea.focus(); } function insertText(str) { const start = textarea.selectionStart; const end = textarea.selectionEnd; const val = textarea.value; textarea.value = val.slice(0, start) + str + val.slice(end); textarea.setSelectionRange(start + str.length, start + str.length); } function toggleCaps() { document.querySelectorAll('.key').forEach(key => { const lbl = key.textContent; if (lbl.length === 1 && /[a-z]/i.test(lbl)) { key.textContent = isCaps ? lbl.toUpperCase() : lbl.toLowerCase(); } }); } })(); </script> </body> </html>How it works:
- We define a
layoutarray representing each row of keys. - We dynamically generate
<div class="key">elements in a CSS Grid. - Clicking a key runs
handleKey(), which inserts/deletes characters in the<textarea>. - Special keys (
Backspace,Enter,Shift, etc.) get custom behavior. - CapsLock/Shift toggles the casing of letter-keys.
Feel free to tweak: • Key styling in the CSS
• Add emojis or custom symbols
• Hook it up to an<input>instead of<textarea>
• Limit the keyboard to numeric/punctuation onlyEnjoy building! 🎉
- We define a
- User
Good start. I want it to be able to use the keyboard to type into other Chrome tabs.
- Assistant
To type into any web page/tab you need to package your keyboard as a Chrome Extension. A pure HTML/JS page can only talk to itself; it has no power to reach into other tabs for security reasons.
Below is a minimal example of how you can:
- Build your on-screen keyboard as an Extension popup (or a separate window)
- Inject a content-script into every page to listen for “key presses” from your popup
- Have the content script synthesize actual keystrokes into the page’s active input
— — —
1) manifest.json
{ "manifest_version": 3, "name": "Universal On-Screen Keyboard", "version": "1.0", "description": "Type into any tab via an on-screen keyboard.", "permissions": [ "activeTab", "scripting" ], "action": { "default_title": "Open On-Screen Keyboard", "default_popup": "popup.html" }, "host_permissions": [ "<all_urls>" ], "background": { "service_worker": "background.js" }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ] }2) popup.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>On-Screen Keyboard</title> <style> body { font-family: sans-serif; padding: 10px; } .key { display:inline-block; margin:3px; padding:10px 15px; background:#eee; border-radius:4px; cursor:pointer; user-select:none; } .key:active { background:#ccc; } </style> </head> <body> <h4>Click to type:</h4> <div id="keys"></div> <script src="popup.js"></script> </body> </html>3) popup.js
const layout = [ ['q','w','e','r','t','y','u','i','o','p'], ['a','s','d','f','g','h','j','k','l'], ['z','x','c','v','b','n','m'], ['Space','Backspace'] ]; const keysContainer = document.getElementById('keys'); layout.forEach(row => { const rowDiv = document.createElement('div'); row.forEach(keyLabel => { const key = document.createElement('div'); key.textContent = keyLabel; key.className = 'key'; key.onclick = () => sendKey(keyLabel); rowDiv.appendChild(key); }); keysContainer.appendChild(rowDiv); }); function sendKey(label) { // send message to the content script in the *active* tab chrome.tabs.query({active: true, currentWindow: true}, tabs => { if (!tabs[0]) return; chrome.tabs.sendMessage( tabs[0].id, {type: 'VK_KEY', key: label} ); }); }4) content.js
// Listen for messages from popup.js chrome.runtime.onMessage.addListener((msg, sender, resp) => { if (msg.type !== 'VK_KEY') return; const key = msg.key; // Find currently focused element, or default to <body> const target = document.activeElement || document.body; // Build a simple "input" or "keydown"/"keypress"/"keyup" event if (key === 'Backspace') { simulateKeyboardEvent('keydown', 'Backspace'); simulateKeyboardEvent('keyup', 'Backspace'); } else if (key === 'Space') { insertText(' '); } else { insertText(key); } function insertText(str) { // If it's an <input> or <textarea>, we can directly modify .value if (target.tagName.match(/INPUT|TEXTAREA/)) { const start = target.selectionStart; const end = target.selectionEnd; const val = target.value; target.value = val.slice(0, start) + str + val.slice(end); const pos = start + str.length; target.setSelectionRange(pos, pos); target.dispatchEvent(new Event('input', {bubbles:true})); } // Otherwise, try to insert into a contenteditable else if (target.isContentEditable) { document.execCommand('insertText', false, str); } } function simulateKeyboardEvent(type, keyName) { const ev = new KeyboardEvent(type, { key: keyName, code: keyName, bubbles: true, cancelable: true }); target.dispatchEvent(ev); } });— — —
How it works
-
manifest.json
• GrantsactiveTab&scriptingso popup can message the current tab
• Injectscontent.jsinto every page (<all_urls>) -
popup.html/js
• Renders your virtual keys
• On click, finds the active tab andchrome.tabs.sendMessage(...)s the key label -
content.js
• Listens for{type: 'VK_KEY'}messages
• Locates the page’sdocument.activeElement
• Either directly edits an<input>/<textarea>’s value or usesexecCommandfor contentEditable
• Optionally also sends realkeydown/keyupevents if you need script listeners
— — —
Limitations & Notes
• This won’t work on Chrome’s internal pages (e.g.chrome://extensions).
• Some sites may block synthetic events or sanitize pasted text.
• You can extend it with Shift/CapsLock, special chars, layouts, etc.Install as an “unpacked extension” under chrome://extensions → “Load unpacked” → point at your folder. Then click the keyboard icon in your toolbar, pick a tab, and start typing! 🚀
- User
Could not load background script 'background.js'. Could not load manifest.
- Assistant
Here’s why you saw that error, and how to fix it:
- In Manifest V3 you must ship the file you declare as your service‐worker (background) script.
- You also must name your manifest exactly
manifest.jsonand place it at the root of your extension folder.
1. Folder structure
Your extension folder should look like this:
/your-extension/ │ ├─ manifest.json ├─ background.js ├─ popup.html ├─ popup.js └─ content.js
2. manifest.json
{ "manifest_version": 3, "name": "Universal On-Screen Keyboard", "version": "1.0", "description": "Type into any tab via an on-screen keyboard.", "permissions": [ "activeTab", "scripting" ], "host_permissions": [ "<all_urls>" ], "action": { "default_title": "Open On-Screen Keyboard", "default_popup": "popup.html" }, "background": { "service_worker": "background.js" }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ] }Make sure that:
- It’s named manifest.json (not
.txtor anything else). - It actually lives in the root of your extension directory.
3. background.js
Even if you don’t need to do much in the background, you still need a dummy service worker file:
// background.js // Just a placeholder. Chrome will load this as the service worker. chrome.runtime.onInstalled.addListener(() => { console.log("🔑 On-Screen Keyboard extension installed"); });That satisfies Chrome’s requirement that the file exists.
4. popup.html & popup.js
<!-- popup.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>On-Screen Keyboard</title> <style> body { font-family: sans-serif; padding: 10px; } .key { display: inline-block; margin: 3px; padding: 10px 15px; background: #eee; border-radius: 4px; cursor: pointer; user-select: none; transition: background 0.1s; } .key:active { background: #ccc; } </style> </head> <body> <h4>Click to type:</h4> <div id="keys"></div> <script src="popup.js"></script> </body> </html>// popup.js const layout = [ ['q','w','e','r','t','y','u','i','o','p'], ['a','s','d','f','g','h','j','k','l'], ['z','x','c','v','b','n','m'], ['Space','Backspace'] ]; const keysContainer = document.getElementById('keys'); layout.forEach(row => { const rowDiv = document.createElement('div'); row.forEach(keyLabel => { const key = document.createElement('div'); key.textContent = keyLabel; key.className = 'key'; key.onclick = () => sendKey(keyLabel); rowDiv.appendChild(key); }); keysContainer.appendChild(rowDiv); }); function sendKey(label) { chrome.tabs.query({active: true, currentWindow: true}, tabs => { if (!tabs[0]) return; chrome.tabs.sendMessage(tabs[0].id, { type: 'VK_KEY', key: label }); }); }
5. content.js
// content.js chrome.runtime.onMessage.addListener((msg) => { if (msg.type !== 'VK_KEY') return; const key = msg.key; const target = document.activeElement; // Helper to insert text into inputs/textareas or contentEditable function insertText(str) { if (!target) return; if (/INPUT|TEXTAREA/.test(target.tagName)) { const start = target.selectionStart, end = target.selectionEnd; const val = target.value; target.value = val.slice(0, start) + str + val.slice(end); const pos = start + str.length; target.setSelectionRange(pos, pos); target.dispatchEvent(new Event('input', { bubbles: true })); } else if (target.isContentEditable) { document.execCommand('insertText', false, str); } } if (key === 'Backspace') { const ev = new KeyboardEvent('keydown', {key:'Backspace',bubbles:true}); target.dispatchEvent(ev); insertText(''); // fallback } else if (key === 'Space') { insertText(' '); } else { insertText(key); } });
6. Load your extension
- Open
chrome://extensions/in Chrome. - Toggle Developer mode on (top-right).
- Click Load unpacked and select your
/your-extension/folder.
Now click the keyboard icon in the toolbar → pick a tab with an input/focusable area → start clicking your on-screen keys and watch them appear in that tab! 🚀
- User
Error: Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
- Assistant
That “Could not establish connection. Receiving end does not exist.” is Chrome telling you that you tried to sendMessage to a tab where no content-script is listening. In practice this can happen if:
- The content script never got injected into that page (matches/host_permissions are wrong, the page is a Chrome internal page, or you haven’t given permission to that domain),
- You send the message before the content script has finished loading,
- Or you’re on a page (e.g. the Chrome Web Store, chrome:// URLs) where extensions cannot run.
Here’s how to bullet-proof your extension so that your popup will always either inject your content.js before messaging, or gracefully recover:
- Make sure your manifest has the right host permissions. For example, if you want to type on every HTTP(S) page:
// manifest.json (v3) { "manifest_version": 3, "name": "Universal On-Screen Keyboard", ... "permissions": ["activeTab","scripting"], "host_permissions": [ "http://*/*", "https://*/*" ], "action": { "default_popup": "popup.html" }, "background": { "service_worker": "background.js" } }- In popup.js, try to send your message. If it fails (because there’s no listener), catch
chrome.runtime.lastError, inject your content script via thechrome.scriptingAPI, and re-send the message:
// popup.js /** * Sends a VK_KEY message to tabId. If there's no listener, * inject content.js then retry. */ function trySendKey(tabId, message) { chrome.tabs.sendMessage(tabId, message, resp => { // if there was any error, assume content.js is not injected if (chrome.runtime.lastError) { // inject the content script chrome.scripting.executeScript({ target: { tabId }, files: ['content.js'] }) .then(() => { // now retry the message chrome.tabs.sendMessage(tabId, message, _ => { if (chrome.runtime.lastError) { console.warn("Still no listener:", chrome.runtime.lastError); } }); }) .catch(err => console.error("Injection failed:", err)); } }); } function sendKey(label) { chrome.tabs.query({active: true, currentWindow: true}, tabs => { if (!tabs[0]) return; trySendKey(tabs[0].id, {type: 'VK_KEY', key: label}); }); } // build your keyboard as before, wiring each key.onclick to sendKey(...)- content.js stays the same—you just need it to be ready to receive when it lands:
// content.js chrome.runtime.onMessage.addListener((msg, sender) => { if (msg.type !== 'VK_KEY') return; const key = msg.key; const target = document.activeElement; function insertText(str) { if (!target) return; if (/(INPUT|TEXTAREA)/.test(target.tagName)) { const s = target.selectionStart, e = target.selectionEnd; const v = target.value; target.value = v.slice(0,s) + str + v.slice(e); const pos = s + str.length; target.setSelectionRange(pos,pos); target.dispatchEvent(new Event('input',{bubbles:true})); } else if (target.isContentEditable) { document.execCommand('insertText', false, str); } } if (key === 'Backspace') { target.dispatchEvent(new KeyboardEvent('keydown',{key:'Backspace',bubbles:true})); insertText(''); } else if (key === 'Space') insertText(' '); else insertText(key); });- Finally, reload your extension in chrome://extensions and test on a normal HTTP or HTTPS page (not chrome:// or the web store).
Now, even if your popup fires before content.js has run, you’ll inject it on-demand and the second sendMessage should succeed.
- User
both are not working.
- Assistant
Here’s a completely different—and much more fool-proof—approach: instead of popping up a separate window (which always steals focus and makes messaging awkward), we inject the keyboard into the page itself as an overlay. That way you never lose focus on your input, you don’t have to worry about
sendMessagetiming, and clicking a key really types into whatever field on the page is active.1) Folder structure
/your-extension/ │ ├─ manifest.json ├─ background.js └─ content.jsNo
popup.htmlorpopup.jsneeded.
2) manifest.json
{ "manifest_version": 3, "name": "Overlay On-Screen Keyboard", "version": "1.0", "description": "Injects a floating on-screen keyboard into every page.", "permissions": [ "scripting" ], "host_permissions": [ "<all_urls>" ], "action": { "default_title": "Toggle On-Screen Keyboard" }, "background": { "service_worker": "background.js" }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ] }- scripting + host_permissions lets us inject & run our code on any HTTP(S) page.
- We declare a
background.jsso that clicking the toolbar button can message the content script. - No popup = no focus stealing.
3) background.js
chrome.action.onClicked.addListener(tab => { // Tell the content script to show/hide the keyboard chrome.tabs.sendMessage(tab.id, { type: 'TOGGLE_KEYBOARD' }); });
4) content.js
(() => { // -- Configuration: keyboard layout -- const layout = [ ['1','2','3','4','5','6','7','8','9','0','Backspace'], ['q','w','e','r','t','y','u','i','o','p'], ['Caps','a','s','d','f','g','h','j','k','l','Enter'], ['Shift','z','x','c','v','b','n','m',',','.','/'], ['Space'] ]; let isCaps = false; let keyboardEl = null; // -- Build the keyboard DOM the first time -- function buildKeyboard() { keyboardEl = document.createElement('div'); keyboardEl.id = 'osk-overlay'; document.body.appendChild(keyboardEl); // basic styling Object.assign(keyboardEl.style, { position: 'fixed', bottom: '10px', left: '50%', transform: 'translateX(-50%)', background: 'rgba(250,250,250,0.95)', border: '1px solid #999', borderRadius: '6px', padding: '8px', display: 'grid', gridGap: '4px', zIndex: 999999, userSelect: 'none' }); // compute columns = max row length const cols = Math.max(...layout.map(r => r.length)); keyboardEl.style.gridTemplateColumns = `repeat(${cols}, 1fr)`; layout.forEach(row => { row.forEach(label => { const key = document.createElement('div'); key.textContent = label; key.className = 'osk-key'; Object.assign(key.style, { padding: '8px 12px', textAlign: 'center', background: '#eee', borderRadius: '4px', cursor: 'pointer', fontFamily: 'sans-serif', fontSize: '14px' }); if (label === 'Space') { key.style.gridColumn = `span ${cols - 2}`; } if (label === 'Backspace' || label === 'Enter' || label === 'Shift' || label === 'Caps') { key.style.background = '#ddd'; } // Prevent the keyboard itself from stealing focus key.addEventListener('mousedown', e => e.preventDefault()); key.addEventListener('click', () => handleKey(label)); keyboardEl.appendChild(key); }); }); } // -- Show/hide keyboard -- function toggleKeyboard() { if (!keyboardEl) buildKeyboard(); keyboardEl.style.display = keyboardEl.style.display === 'none' ? 'grid' : 'none'; } // -- Handle key presses -- function handleKey(label) { const target = document.activeElement; if (!target) return; // helper to insert text into inputs/areas or contentEditable const insertText = txt => { if (target.tagName.match(/INPUT|TEXTAREA/)) { const s = target.selectionStart, e = target.selectionEnd, v = target.value; target.value = v.slice(0,s) + txt + v.slice(e); target.setSelectionRange(s+txt.length, s+txt.length); target.dispatchEvent(new Event('input', { bubbles: true })); } else if (target.isContentEditable) { document.execCommand('insertText', false, txt); } }; switch(label) { case 'Backspace': // delete one character if (/INPUT|TEXTAREA/.test(target.tagName)) { const s = target.selectionStart, e = target.selectionEnd, v = target.value; if (s>0) { target.value = v.slice(0,s-1) + v.slice(e); target.setSelectionRange(s-1, s-1); target.dispatchEvent(new Event('input', { bubbles: true })); } } else { // for contentEditable we just send a backspace event target.dispatchEvent(new KeyboardEvent('keydown',{key:'Backspace',bubbles:true})); } break; case 'Enter': insertText('\n'); break; case 'Space': insertText(' '); break; case 'Caps': isCaps = !isCaps; refreshCaps(); break; case 'Shift': isCaps = true; refreshCaps(); // auto‐clear shift after a keypress setTimeout(() => { isCaps = false; refreshCaps(); }, 300); break; default: // letter or digit const ch = (isCaps ? label.toUpperCase() : label.toLowerCase()); insertText(ch); } target.focus(); } // update letter keys to show caps state function refreshCaps() { keyboardEl.querySelectorAll('.osk-key').forEach(k => { const t = k.textContent; if (t.length === 1 && /[a-z]/i.test(t)) { k.textContent = isCaps ? t.toUpperCase() : t.toLowerCase(); } k.style.background = (t==='Caps' && isCaps) ? '#bbb' : (['Backspace','Enter','Shift','Caps'].includes(t) ? '#ddd' : '#eee'); }); } // listen for the toolbar button click chrome.runtime.onMessage.addListener((msg) => { if (msg.type === 'TOGGLE_KEYBOARD') toggleKeyboard(); }); // Initially hidden })();How this solves your “connection” & “focus” problems
- There is no popup, so no
sendMessage ↔ content.jsrace. The content script is always there. - Clicking a key does not move focus away from the page’s input—
mousedowncallspreventDefault(). - You truly are in the page, so modifying
document.activeElement.valueorexecCommand('insertText')works as expected. - Hides/shows on every toolbar-button click.
5) Usage
- Go to
chrome://extensions/, turn on Developer mode, click Load unpacked → select your/your-extension/folder. - Browse to any HTTP(S) page with an
<input>,<textarea>or acontenteditablearea. - Click the keyboard icon in your toolbar. A little overlay keyboard appears at the bottom.
- Click your page’s input to focus it, then click the on-screen keys—your text goes right in! 🎉
Feel free to tweak the layout, styling, position or add extra symbols.
- User
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
- Assistant
Let’s ditch the whole “popup → message → content-script race” thing and just inject your keyboard overlay into the page on demand. You never lose focus, you never race against a missing listener, and you don’t need a popup at all. Whenever you click the toolbar icon, Chrome will inject (or re-inject) your
content.js, which immediately toggles the on-screen keyboard.
1) Folder structure
/your-extension/ │ ├─ manifest.json ├─ background.js └─ content.jsNo
popup.htmlorpopup.jsneeded.
2) manifest.json
{ "manifest_version": 3, "name": "Overlay On-Screen Keyboard", "version": "1.0", "description": "Floating keyboard injected into any page.", "permissions": [ "scripting" ], "host_permissions": [ "<all_urls>" ], "action": { "default_title": "Toggle On-Screen Keyboard" }, "background": { "service_worker": "background.js" } }Notes:
•
scripting+<all_urls>lets you inject into any HTTP/S (or file:// if you enable “Allow access to file URLs” in chrome://extensions).
• Nocontent_scriptsentry—everything happens viachrome.scripting.executeScript.
3) background.js
// background.js chrome.action.onClicked.addListener((tab) => { // Inject our content.js into the active tab chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] }).catch(err => { console.error("Injection failed:", err); }); });Every time you click the toolbar button, Chrome will run
content.jsin the context of the page.
4) content.js
// content.js (function() { // If we’ve injected before, toggle off + remove: const existing = document.getElementById('osk-overlay'); if (existing) { existing.remove(); return; } // 1) Build the keyboard container const wrapper = document.createElement('div'); wrapper.id = 'osk-overlay'; document.body.appendChild(wrapper); // 2) Style it Object.assign(wrapper.style, { position: 'fixed', bottom: '10px', left: '50%', transform: 'translateX(-50%)', background: 'rgba(250,250,250,0.97)', border: '1px solid #888', borderRadius: '6px', padding: '8px', zIndex: 2147483647, // max z-index display: 'grid', gridGap: '4px', userSelect: 'none' }); // 3) Define your layout const layout = [ ['1','2','3','4','5','6','7','8','9','0','Backspace'], ['q','w','e','r','t','y','u','i','o','p'], ['Caps','a','s','d','f','g','h','j','k','l','Enter'], ['Shift','z','x','c','v','b','n','m',',','.','/'], ['Space'] ]; // Compute max columns const cols = Math.max(...layout.map(r => r.length)); wrapper.style.gridTemplateColumns = `repeat(${cols}, 1fr)`; let isCaps = false; // 4) Build keys layout.forEach(row => { row.forEach(label => { const key = document.createElement('div'); key.textContent = label; key.className = 'osk-key'; Object.assign(key.style, { padding: '8px 12px', textAlign: 'center', background: ['Backspace','Enter','Shift','Caps'].includes(label) ? '#ddd' : '#eee', borderRadius: '4px', cursor: 'pointer', fontFamily: 'sans-serif', fontSize: '14px' }); // Space bar spans many columns if (label === 'Space') { key.style.gridColumn = `span ${cols - 2}`; } // Prevent losing focus on your page’s input key.addEventListener('mousedown', e => e.preventDefault()); key.addEventListener('click', () => onKey(label)); wrapper.appendChild(key); }); }); // 5) Key handler function onKey(label) { const target = document.activeElement; if (!target) return; // helper to insert text const insert = txt => { if (/INPUT|TEXTAREA/.test(target.tagName)) { const s = target.selectionStart, e = target.selectionEnd, v = target.value; target.value = v.slice(0,s) + txt + v.slice(e); target.setSelectionRange(s+txt.length, s+txt.length); target.dispatchEvent(new Event('input', { bubbles: true })); } else if (target.isContentEditable) { document.execCommand('insertText', false, txt); } }; switch(label) { case 'Backspace': if (/INPUT|TEXTAREA/.test(target.tagName)) { const s = target.selectionStart, e = target.selectionEnd, v = target.value; if (s > 0) { target.value = v.slice(0,s-1) + v.slice(e); target.setSelectionRange(s-1,s-1); target.dispatchEvent(new Event('input',{bubbles:true})); } } else { // fallback for contenteditable target.dispatchEvent(new KeyboardEvent('keydown',{key:'Backspace',bubbles:true})); } break; case 'Enter': insert('\n'); break; case 'Space': insert(' '); break; case 'Caps': isCaps = !isCaps; refreshCaps(); break; case 'Shift': isCaps = true; refreshCaps(); setTimeout(() => { isCaps = false; refreshCaps() }, 200); break; default: const ch = isCaps ? label.toUpperCase() : label.toLowerCase(); insert(ch); } target.focus(); } // 6) Update letters on Caps/Shift function refreshCaps() { wrapper.querySelectorAll('.osk-key').forEach(k => { const t = k.textContent; if (t.length === 1 && /[a-z]/i.test(t)) { k.textContent = isCaps ? t.toUpperCase() : t.toLowerCase(); } // Highlight CAPS if (t === 'Caps') { k.style.background = isCaps ? '#bbb' : '#ddd'; } }); } })();
Why this finally works without the “Could not establish connection” error
- No popup → no messaging
You never dochrome.tabs.sendMessage, so there is no “receiving end” error. - Content-script is ephemeral
You injectcontent.jsonly when you click the toolbar icon—and it runs immediately. - Focus is preserved
We prevent the keyboard from grabbing focus (mousedown.preventDefault()), so whatever input was already focused stays ready to receive characters. - Toggle built-in
The first time you inject it, the keyboard appears. The next time you inject it, the script finds#osk-overlayand removes it.
Installation
- Go to chrome://extensions/
- Toggle Developer mode
- Click Load unpacked → select your
/your-extension/folder - Browse to any HTTP(S) page (or file:// if you enabled it) with an
<input>,<textarea>or a contenteditable - Click the new toolbar icon to show/hide your on-screen keyboard and start typing!
Let me know if you still hit any snags—this pattern is bullet-proof against “no listener” races! 🚀
- No popup → no messaging
- User
It's working. Please add a shortcut key for activation eg control shift k. Also add a button for closing the keyboard.
- Assistant
Below is a minimal diff‐style update to add both:
- A Ctrl + Shift + K shortcut (via the
commandsAPI) - A little ✕ close-button in the overlay itself
1) manifest.json
{ "manifest_version": 3, "name": "Overlay On-Screen Keyboard", "version": "1.0", "description": "Floating keyboard injected into any page.", "permissions": [ "scripting" ], "host_permissions": [ "<all_urls>" ], "action": { "default_title": "Toggle On-Screen Keyboard" }, "background": { "service_worker": "background.js" }, // ← NEW: define a named command for the keyboard shortcut "commands": { "toggle-keyboard": { "suggested_key": { "default": "Ctrl+Shift+K" }, "description": "Show or hide the on-screen keyboard" } } }
2) background.js
// background.js /** * Injects (or re-injects) content.js into the page. * Since content.js is toggle-aware, a second injection * will remove the overlay instead. */ function toggleKeyboard(tabId) { chrome.scripting.executeScript({ target: { tabId }, files: ['content.js'] }) .catch(err => console.error("Injection failed:", err)); } // 2a) Toolbar-icon click also toggles the keyboard chrome.action.onClicked.addListener(tab => { if (!tab.id) return; toggleKeyboard(tab.id); }); // 2b) Listen for our Ctrl+Shift+K command chrome.commands.onCommand.addListener(command => { if (command === 'toggle-keyboard') { // find the active tab in the current window chrome.tabs.query({ active: true, currentWindow: true }) .then(tabs => { if (tabs[0] && tabs[0].id != null) { toggleKeyboard(tabs[0].id); } }) .catch(console.error); } });
3) content.js
// content.js (() => { // If already injected, remove the keyboard (toggle-off). const existing = document.getElementById('osk-overlay'); if (existing) { existing.remove(); return; } // 1) Create overlay container const wrapper = document.createElement('div'); wrapper.id = 'osk-overlay'; document.body.appendChild(wrapper); // 2) Basic styling Object.assign(wrapper.style, { position: 'fixed', bottom: '10px', left: '50%', transform: 'translateX(-50%)', background: 'rgba(250,250,250,0.97)', border: '1px solid #888', borderRadius: '6px', padding: '8px', zIndex: 2147483647, display: 'grid', gridGap: '4px', userSelect: 'none' }); // 3) Add a close-button (✕) in the top-right corner const btnClose = document.createElement('div'); btnClose.textContent = '✕'; Object.assign(btnClose.style, { position: 'absolute', top: '4px', right: '6px', cursor: 'pointer', fontSize: '14px', color: '#555', userSelect: 'none' }); btnClose.addEventListener('mousedown', e => e.preventDefault()); btnClose.addEventListener('click', () => wrapper.remove()); wrapper.appendChild(btnClose); // 4) Keyboard layout const layout = [ ['1','2','3','4','5','6','7','8','9','0','Backspace'], ['q','w','e','r','t','y','u','i','o','p'], ['Caps','a','s','d','f','g','h','j','k','l','Enter'], ['Shift','z','x','c','v','b','n','m',',','.','/'], ['Space'] ]; // 5) Grid columns = widest row const cols = Math.max(...layout.map(r => r.length)); wrapper.style.gridTemplateColumns = `repeat(${cols}, 1fr)`; let isCaps = false; // 6) Build each key layout.forEach(row => { row.forEach(label => { const key = document.createElement('div'); key.textContent = label; key.className = 'osk-key'; Object.assign(key.style, { padding: '8px 12px', textAlign: 'center', background: ['Backspace','Enter','Shift','Caps'].includes(label) ? '#ddd' : '#eee', borderRadius: '4px', cursor: 'pointer', fontFamily: 'sans-serif', fontSize: '14px' }); if (label === 'Space') { key.style.gridColumn = `span ${cols - 2}`; } // prevent stealing focus key.addEventListener('mousedown', e => e.preventDefault()); key.addEventListener('click', () => onKey(label)); wrapper.appendChild(key); }); }); // 7) Key‐press handler function onKey(label) { const tgt = document.activeElement; if (!tgt) return; const insert = txt => { if (/INPUT|TEXTAREA/.test(tgt.tagName)) { const s = tgt.selectionStart, e = tgt.selectionEnd, v = tgt.value; tgt.value = v.slice(0,s) + txt + v.slice(e); const pos = s + txt.length; tgt.setSelectionRange(pos,pos); tgt.dispatchEvent(new Event('input',{bubbles:true})); } else if (tgt.isContentEditable) { document.execCommand('insertText', false, txt); } }; switch(label) { case 'Backspace': if (/INPUT|TEXTAREA/.test(tgt.tagName)) { const s = tgt.selectionStart, e = tgt.selectionEnd, v = tgt.value; if (s > 0) { tgt.value = v.slice(0,s-1) + v.slice(e); tgt.setSelectionRange(s-1,s-1); tgt.dispatchEvent(new Event('input',{bubbles:true})); } } else { tgt.dispatchEvent(new KeyboardEvent('keydown',{key:'Backspace',bubbles:true})); } break; case 'Enter': insert('\n'); break; case 'Space': insert(' '); break; case 'Caps': isCaps = !isCaps; refreshCaps(); break; case 'Shift': isCaps = true; refreshCaps(); setTimeout(()=>{ isCaps=false; refreshCaps(); }, 200); break; default: const ch = isCaps ? label.toUpperCase() : label.toLowerCase(); insert(ch); } tgt.focus(); } // 8) Refresh letter-key labels when Caps/Shift toggles function refreshCaps() { wrapper.querySelectorAll('.osk-key').forEach(k => { const t = k.textContent; if (t.length===1 && /[a-z]/i.test(t)) { k.textContent = isCaps ? t.toUpperCase() : t.toLowerCase(); } // highlight Caps when active if (t==='Caps') { k.style.background = isCaps ? '#bbb' : '#ddd'; } }); } })();
Reload your unpacked extension, and now:
- Press Ctrl + Shift + K (or click the toolbar icon) → overlay appears
- The little ✕ in the top-right closes it immediately
- Caps/Shift/Backspace/Space/etc. work as before
Enjoy! 🚀
- A Ctrl + Shift + K shortcut (via the
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.