Fix problems that could not get parent url and selected text in iframe

This commit is contained in:
sienori 2019-02-23 22:10:18 +09:00
parent a1ae0a0167
commit a90ef23f6a
3 changed files with 17 additions and 7 deletions

View file

@ -50,10 +50,10 @@ const translateSelectedText = async () => {
}; };
const translatePage = async () => { const translatePage = async () => {
const tab = (await browser.tabs.query({ active: true }))[0]; 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 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}`; const translationUrl = `https://translate.google.com/translate?hl=${targetLang}&sl=auto&u=${encodedPageUrl}`;
browser.tabs.create({ browser.tabs.create({

View file

@ -101,10 +101,19 @@ export default class TranslateContainer extends Component {
}; };
handleMessage = async request => { handleMessage = async request => {
const empty = new Promise(resolve => {
setTimeout(() => {
return resolve("");
}, 100);
});
switch (request.message) { switch (request.message) {
case "getTabInfo": case "getTabUrl":
const tabInfo = { url: location.href, selectedText: this.selectedText }; if (window == window.parent) return location.href;
return tabInfo; else return empty;
case "getSelectedText":
if (this.selectedText.length === 0) return empty;
else return this.selectedText;
case "translateSelectedText": case "translateSelectedText":
this.selectedText = getSelectedText(); this.selectedText = getSelectedText();
if (this.selectedText.length === 0) return; if (this.selectedText.length === 0) return;

View file

@ -12,8 +12,9 @@ import "../styles/PopupPage.scss";
const getTabInfo = async () => { const getTabInfo = async () => {
try { try {
const tab = (await browser.tabs.query({ currentWindow: true, active: true }))[0]; const tab = (await browser.tabs.query({ currentWindow: true, active: true }))[0];
const tabInfo = await browser.tabs.sendMessage(tab.id, { message: "getTabInfo" }); const tabUrl = await browser.tabs.sendMessage(tab.id, { message: "getTabUrl" });
return tabInfo; const selectedText = await browser.tabs.sendMessage(tab.id, { message: "getSelectedText" });
return { url: tabUrl, selectedText: selectedText };
} catch (e) { } catch (e) {
return { url: "", selectedText: "" }; return { url: "", selectedText: "" };
} }