Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safari extension - Too many injected scripts responding to message

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?

like image 792
Philipp Avatar asked Oct 15 '22 04:10

Philipp


1 Answers

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.

like image 89
chulster Avatar answered Oct 18 '22 13:10

chulster