From 460d306f60fa745368c8249e4bc4bdb0d0448f25 Mon Sep 17 00:00:00 2001 From: siikamiika Date: Mon, 10 Feb 2020 01:16:06 +0200 Subject: update popup search with chrome.tabs.sendMessage --- ext/bg/js/backend.js | 4 +++- ext/bg/js/search.js | 23 ++++++++++++++++++++--- 2 files changed, 23 insertions(+), 4 deletions(-) (limited to 'ext/bg/js') diff --git a/ext/bg/js/backend.js b/ext/bg/js/backend.js index adfb4f10..668d1fb7 100644 --- a/ext/bg/js/backend.js +++ b/ext/bg/js/backend.js @@ -619,7 +619,9 @@ class Backend { if (tab !== null) { await Backend._focusTab(tab); if (queryParams.query) { - await new Promise((resolve) => chrome.tabs.update(tab.id, {url}, resolve)); + await new Promise((resolve) => chrome.tabs.sendMessage( + tab.id, {action: 'searchQueryUpdate', params: {query: queryParams.query}}, resolve + )); } return true; } diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index b6a1e66a..37c96934 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -109,10 +109,12 @@ class DisplaySearch extends Display { }); } + chrome.runtime.onMessage.addListener(this.onRuntimeMessage.bind(this)); + window.addEventListener('popstate', (e) => this.onPopState(e)); window.addEventListener('copy', (e) => this.onCopy(e)); - this.clipboardMonitor.onClipboardText = (text) => this.onClipboardText(text); + this.clipboardMonitor.onClipboardText = (text) => this.onExternalSearchUpdate(text); this.updateSearchButton(); } catch (e) { @@ -163,6 +165,15 @@ class DisplaySearch extends Display { this.onSearchQueryUpdated(this.query.value, false); } + onRuntimeMessage({action, params}, sender, callback) { + const handler = DisplaySearch._runtimeMessageHandlers.get(action); + if (typeof handler !== 'function') { return false; } + + const result = handler(this, params, sender); + callback(result); + return false; + } + onKeyDown(e) { const key = Display.getKeyFromEvent(e); const ignoreKeys = DisplaySearch.onKeyDownIgnoreKeys; @@ -192,9 +203,11 @@ class DisplaySearch extends Display { this.clipboardMonitor.setPreviousText(document.getSelection().toString().trim()); } - onClipboardText(text) { + onExternalSearchUpdate(text) { this.setQuery(text); - window.history.pushState(null, '', `${window.location.pathname}?query=${encodeURIComponent(text)}`); + const url = new URL(window.location.href); + url.searchParams.set('query', text); + window.history.pushState(null, '', url.toString()); this.onSearchQueryUpdated(this.query.value, true); } @@ -340,4 +353,8 @@ DisplaySearch.onKeyDownIgnoreKeys = { 'Shift': [] }; +DisplaySearch._runtimeMessageHandlers = new Map([ + ['searchQueryUpdate', (self, {query}) => { self.onExternalSearchUpdate(query); }] +]); + DisplaySearch.instance = DisplaySearch.create(); -- cgit v1.2.3