From 704864b7b2365de488150c947d50e27c97d3bc4c Mon Sep 17 00:00:00 2001 From: siikamiika Date: Sat, 26 Oct 2019 18:15:28 +0300 Subject: add clipboard monitor to search page Related to issue #262 about APIs --- ext/bg/js/search.js | 44 +++++++++++++++++++++++++++++++++++++++++++- ext/bg/search.html | 9 ++++++++- ext/manifest.json | 1 + 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index d66e68b8..2d130522 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -29,8 +29,13 @@ class DisplaySearch extends Display { this.search = document.querySelector('#search'); this.query = document.querySelector('#query'); this.intro = document.querySelector('#intro'); + this.clipboardMonitorCheck = document.querySelector('#clipboard-monitor'); + this.introVisible = true; this.introAnimationTimer = null; + + this.clipboardMonitorIntervalId = null; + this.clipboardPrevText = null; } static create() { @@ -57,10 +62,20 @@ class DisplaySearch extends Display { window.wanakana.bind(this.query); } + if (this.clipboardMonitorCheck !== null) { + this.clipboardMonitorCheck.addEventListener('change', (e) => { + if (e.target.checked) { + this.startClipboardMonitor(); + } else { + this.stopClipboardMonitor(); + } + }); + } window.addEventListener('popstate', (e) => this.onPopState(e)); this.updateSearchButton(); + this.initClipboardMonitor(); } catch (e) { this.onError(e); } @@ -93,7 +108,9 @@ class DisplaySearch extends Display { return; } - e.preventDefault(); + if (e) { + e.preventDefault(); + } const query = this.query.value; const queryString = query.length > 0 ? `?query=${encodeURIComponent(query)}` : ''; @@ -182,6 +199,31 @@ class DisplaySearch extends Display { } } + initClipboardMonitor() { + // ignore copy from search page + window.addEventListener('copy', (e) => { + this.clipboardPrevText = document.getSelection().toString().trim(); + }); + } + + startClipboardMonitor() { + this.clipboardMonitorIntervalId = setInterval(async () => { + const curText = (await navigator.clipboard.readText()).trim(); + if (curText && (curText !== this.clipboardPrevText)) { + this.query.value = curText; + this.onSearch(); + this.clipboardPrevText = curText; + } + }, 100); + } + + stopClipboardMonitor() { + if (this.clipboardMonitorIntervalId) { + clearInterval(this.clipboardMonitorIntervalId); + this.clipboardMonitorIntervalId = null; + } + } + getOptionsContext() { return this.optionsContext; } diff --git a/ext/bg/search.html b/ext/bg/search.html index 9d28b358..1e650be0 100644 --- a/ext/bg/search.html +++ b/ext/bg/search.html @@ -19,7 +19,14 @@

Search your installed dictionaries by entering a Japanese expression into the field below.

-
+
+ + + + +
+ + diff --git a/ext/manifest.json b/ext/manifest.json index e913c2b0..2b7fc105 100644 --- a/ext/manifest.json +++ b/ext/manifest.json @@ -41,6 +41,7 @@ "permissions": [ "", "storage", + "clipboardRead", "clipboardWrite", "unlimitedStorage" ], -- cgit v1.2.3