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 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({

View file

@ -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;

View file

@ -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: "" };
}