Skip to content

Commit

Permalink
Improve element detection for certain sites & reduce focus delay
Browse files Browse the repository at this point in the history
By initiating at DOMContentLoaded instead of load elements can be focused without waiting for whole page to load. Content script will also retry the init function up to three times with a 100ms delay if no elements were found (which seems to happen for certain SPA and AMP sites)
  • Loading branch information
adrianhak committed Aug 21, 2021
1 parent 648490b commit 6231f4d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
18 changes: 16 additions & 2 deletions src/content_script.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const inputTypes = ['search','text'];
let inputEls;
let targetElement;
let contextMenuElement; // To be set by event listener
let retryCount = 0;

// Check if host is blacklisted by user
isDisabled(location.hostname,(isDisabled) => {
Expand All @@ -14,15 +15,28 @@ isDisabled(location.hostname,(isDisabled) => {
if (document.readyState == 'complete') {
init();
} else {
window.addEventListener('load',function load() {
window.removeEventListener('load',load,false);
window.addEventListener('DOMContentLoaded',function domLoaded() {
window.removeEventListener('DOMContentLoaded',domLoaded,false);
init();
});
window.addEventListener('load', function load() {
window.removeEventListener('load',load,false);
// Refocus element if focus changed between DOMContentLoaded & load (see https://reddit.com)
if (targetElement && document.activeElement != targetElement) {
focusElement(targetElement);
}
});
}
});

function init() {
inputEls = [...document.getElementsByTagName('input')];
// If no elements were found, try again in case DOM wasn't fully loaded (see https://justwatch.com)
if (inputEls.length == 0 && retryCount < 3) {
retryCount++;
setTimeout(() => init(),100);
return;
}
// First find out if user has a custom mapping for this hostname
searchMappings('custom',(element) => {
if (element == null) {
Expand Down
4 changes: 2 additions & 2 deletions src/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"manifest_version": 2,
"name": "Autofocus",
"description": "Search faster - Puts the cursor in the search box on page load",
"version": "0.1.1",
"version": "0.2",
"icons" : {
"16": "img/icon-16.png",
"48": "img/icon-48.png",
Expand All @@ -13,7 +13,7 @@
{
"matches": ["<all_urls>"],
"js": ["content_script.js"],
"run_at": "document_end"
"run_at": "document_start"
}
],
"browser_action": {
Expand Down

0 comments on commit 6231f4d

Please sign in to comment.