开发者

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 pr开发者_如何学Pythonoblem 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.


Maybe you could check that the page in which the script is injected is not inside a frame:

if (window == window.parent) { /* you're not inside a frame! */ }

I'm not sure if it works from inside <object> tags embedding HTML though. Chances are that yes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜