I am trying to code a safari extension similar to Bubble Translate for Chrome.
when you click a button on the toolbar, it automatically translates the text currently selected to the language of your choice using the Google language API.
The problem I have is the following:
The script does not just get injected into the main page but also into ads and similar stuff that is embedded into the page. Due to that, the selected text gets translated multiple times because all the embedded scripts in one page respond to the message.
How can I make sure that the script is injected only into the right page or only the right page responds?
When the global script responds to the message from the injected script, include the target tab's url in the response message, like so:
var message = {
translation: result.translation,
url: event.target.url
}
event.target.page.dispatchMessage("displayTranslation", message);
Then, in the injected script's message handler, check that the url passed in the message matches the page url, like so:
if (event.name === "displayTranslation" &&
event.message.url === window.location.href) {
alert(event.message.translation);
}
That way, only the script in the frame that originated the request will act on the response.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With