83 lines
2.2 KiB
JavaScript
83 lines
2.2 KiB
JavaScript
class KeyHinter {
|
|
constructor() {
|
|
this.number = 0;
|
|
this.nodes = {};
|
|
|
|
this.mappings = {}
|
|
}
|
|
|
|
// Highlight
|
|
highlight() {
|
|
if (this.number !== 0)
|
|
return false
|
|
|
|
this.listenKeybinds()
|
|
|
|
var _this = this;
|
|
document.querySelectorAll('a, form').forEach(function(nodeEl) {
|
|
_this.number++;
|
|
_this.nodes[_this.number] = nodeEl;
|
|
|
|
var el = _this.generateLabelFor(nodeEl);
|
|
|
|
if (nodeEl.nodeName == 'A') {
|
|
el.classList.add('keyhinter-label-anchor');
|
|
} else if (nodeEl.nodeName == 'FORM') {
|
|
el.classList.add('keyhinter-label-form');
|
|
}
|
|
|
|
el.textContent = _this.number;
|
|
el.setAttribute('data-keyhinter-number', _this.number);
|
|
|
|
document.body.appendChild(el);
|
|
})
|
|
}
|
|
|
|
// Label generation
|
|
generateLabelFor(node) {
|
|
var el = document.createElement('div');
|
|
var nodePosition = node.getBoundingClientRect();
|
|
el.classList.add('keyhinter-label');
|
|
el.style.left = nodePosition.left + 'px';
|
|
el.style.top = nodePosition.top + 'px';
|
|
return el;
|
|
}
|
|
|
|
// Keybinds
|
|
listenKeybinds() {
|
|
var _this = this;
|
|
document.onkeydown = function(event) {
|
|
if (event.keyCode == 27) {
|
|
console.log('Esc')
|
|
event.preventDefault();
|
|
_this.destroy();
|
|
}
|
|
}
|
|
}
|
|
|
|
stopListeningKeybinds() {
|
|
document.onkeydown = null;
|
|
}
|
|
|
|
// Non-safe methods
|
|
destroy() {
|
|
document.querySelectorAll('.keyhinter-label').forEach(function(node){
|
|
document.body.removeChild(node);
|
|
})
|
|
this.stopListeningKeybinds();
|
|
stage = new KeyHinter()
|
|
}
|
|
}
|
|
|
|
var stage = new KeyHinter();
|
|
|
|
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
|
|
// If the received message has the expected format...
|
|
console.log(msg, sender, sendResponse)
|
|
if (msg.action === 'start_keyhinter') {
|
|
// Call the specified callback, passing
|
|
// the web-page's DOM content as argument
|
|
stage.highlight();
|
|
}
|
|
});
|