Safari 扩展 - 响应消息的注入脚本过多
我正在尝试编写一个类似于 Chrome 的 Bubble Translate 的 safari 扩展程序。
当您单击工具栏上的按钮时,它会使用 Google 语言 API 自动将当前选择的文本翻译为您选择的语言。
我遇到的问题如下:
脚本不仅会注入到主页中,还会注入到嵌入到页面中的广告和类似内容中。因此,所选文本会被多次翻译,因为一页中的所有嵌入脚本都会响应该消息。
如何确保脚本仅注入到正确的页面或仅正确的页面响应?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当全局脚本响应来自注入脚本的消息时,在响应消息中包含目标选项卡的 url,如下所示: 然后
,在注入脚本的消息处理程序中,检查消息中传递的 url 是否与页面 url 匹配,如下所示:
这样,只有发起请求的框架中的脚本才会对响应起作用。
When the global script responds to the message from the injected script, include the target tab's url in the response message, like so:
Then, in the injected script's message handler, check that the url passed in the message matches the page url, like so:
That way, only the script in the frame that originated the request will act on the response.
也许您可以检查注入脚本的页面是否不在框架内:
但我不确定它是否可以在嵌入 HTML 的
Maybe you could check that the page in which the script is injected is not inside a frame:
I'm not sure if it works from inside
<object>
tags embedding HTML though. Chances are that yes.