English 中文(简体)
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?

问题回答

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.





相关问题
Font Rendering between Mozilla and webkit

I m not sure if this has anything to do with the recent Safari update, but I m beginning to notice this a lot. There is a drastic difference in the way each browser is rendering fonts. for instance, ...

How i can track Safari activity from my application

I have to develop an application to monitor Safari activity like all open url , tabs on particular window and loding time of particular url. I also need to track online streaming that is happening on ...

Drop down background url in Safari Issue

selectBox.selectCSS { background: url(/Images/replacementSelectBackground.png) top left no-repeat height:auto; } I have an issue in Safari only where the image is not rendering on top ...

CSS specific for Safari

How do you target specifically safari in css with styles?

How to get a flash url in a webpage using a webframe?

As we know , When we load frame from webpage of safari, we will invoke the delegate methods of webkit informal protocol(WebFrameLoadDelegate): webView:didStartProvisionalLoadForFrame: webView:...

热门标签