diff --git a/src/background/keyboardShortcuts.js b/src/background/keyboardShortcuts.js index b506289..0236fc7 100644 --- a/src/background/keyboardShortcuts.js +++ b/src/background/keyboardShortcuts.js @@ -50,10 +50,10 @@ const translateSelectedText = async () => { }; const translatePage = async () => { const tab = (await browser.tabs.query({ active: true }))[0]; - const tabInfo = await browser.tabs.sendMessage(tab.id, { message: "getTabInfo" }); + const tabUrl = await browser.tabs.sendMessage(tab.id, { message: "getTabUrl" }); const targetLang = getSettings("targetLang"); - const encodedPageUrl = encodeURIComponent(tabInfo.url); + const encodedPageUrl = encodeURIComponent(tabUrl); const translationUrl = `https://translate.google.com/translate?hl=${targetLang}&sl=auto&u=${encodedPageUrl}`; browser.tabs.create({ diff --git a/src/content/components/TranslateContainer.js b/src/content/components/TranslateContainer.js index ddbd8d9..fe7b65c 100644 --- a/src/content/components/TranslateContainer.js +++ b/src/content/components/TranslateContainer.js @@ -101,10 +101,19 @@ export default class TranslateContainer extends Component { }; handleMessage = async request => { + const empty = new Promise(resolve => { + setTimeout(() => { + return resolve(""); + }, 100); + }); + switch (request.message) { - case "getTabInfo": - const tabInfo = { url: location.href, selectedText: this.selectedText }; - return tabInfo; + case "getTabUrl": + if (window == window.parent) return location.href; + else return empty; + case "getSelectedText": + if (this.selectedText.length === 0) return empty; + else return this.selectedText; case "translateSelectedText": this.selectedText = getSelectedText(); if (this.selectedText.length === 0) return; diff --git a/src/popup/components/PopupPage.js b/src/popup/components/PopupPage.js index 3ee48ae..1bb2321 100644 --- a/src/popup/components/PopupPage.js +++ b/src/popup/components/PopupPage.js @@ -12,8 +12,9 @@ import "../styles/PopupPage.scss"; const getTabInfo = async () => { try { const tab = (await browser.tabs.query({ currentWindow: true, active: true }))[0]; - const tabInfo = await browser.tabs.sendMessage(tab.id, { message: "getTabInfo" }); - return tabInfo; + const tabUrl = await browser.tabs.sendMessage(tab.id, { message: "getTabUrl" }); + const selectedText = await browser.tabs.sendMessage(tab.id, { message: "getSelectedText" }); + return { url: tabUrl, selectedText: selectedText }; } catch (e) { return { url: "", selectedText: "" }; }