Skip to content

Instantly share code, notes, and snippets.

@lydell
Last active February 18, 2017 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lydell/a730c852fdb37f6d8f1f30968f3b591b to your computer and use it in GitHub Desktop.
Save lydell/a730c852fdb37f6d8f1f30968f3b591b to your computer and use it in GitHub Desktop.
WebExtension .focus() tests
"use strict";
function onError(error) {
console.error(`Error: ${error}`);
}
function sendMessageToTabs(tabs) {
for (let tab of tabs) {
browser.tabs.sendMessage(
tab.id,
{greeting: "Hi from background script"}
).then(response => {
console.log("Message from the content script:");
console.log(response.response);
}).catch(onError);
}
}
browser.commands.onCommand.addListener(name => {
console.log("command", name);
browser.tabs.query({
currentWindow: true,
active: true
}).then(sendMessageToTabs).catch(onError);
})
"use strict";
browser.runtime.onMessage.addListener(request => {
console.log("Message from the background script:");
console.log(request.greeting);
document.body.style.border = "2px solid red";
document.body.focus();
var firstInput = document.querySelector("input:not([type=hidden])");
if (firstInput) {
firstInput.style.border = "2px solid red";
firstInput.focus();
}
return Promise.resolve({response: "Hi from content script"});
});
{
"manifest_version": 2,
"name": "webextension-test",
"version": "0.0.0",
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"browser_action": {
"default_popup": "popup.html"
},
"commands": {
"_execute_browser_action": {
"suggested_key": {
"default": "Ctrl+E"
}
},
"test": {
"suggested_key": {
"default": "Ctrl+Shift+E"
}
}
}
}
<p id="text">popup</p>
<input id="input" autofocus>
<script src="popup.js"></script>
"use strict";
setTimeout(() => {
document.querySelector("body").focus();
text.textContent = "focused?";
}, 100);
document.addEventListener("keydown", event => {
text.textContent = event.key;
}, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment