willyMon
willyMon

Reputation: 639

how to enable Safari Extensions when using a web view

I am using a Web view in my application, instead of open a Safari browser instance, so I noticed that Safari extensions doesn't work. Is there a possibility to enable this feature when using a custom web view in a Cocoa Application?

The reason by which I need to use Safari extensions is to inject javascript to whatever web page is loaded at one moment, so if is there another approach to do it without using extensions, welcome any suggestions or samples.

Upvotes: 2

Views: 1423

Answers (1)

chulster
chulster

Reputation: 2829

There's no way to use Safari extensions in a web view.

If your script isn't too big, how about formatting it as a "javascript:" bookmarklet and setting the web view's location to it?

[Edit: Stuff below added in response to questioner's request for "a bit more about that technique".]

Say you want to change the background color of the page to yellow and all the text to red. The javascript to do that would be something like:

document.body.style.backgroundColor = "yellow";
document.body.style.color = "red !important";

To turn the script into a bookmarklet, you just:

  1. Wrap it in an anonymous function,
  2. remove all line breaks,
  3. (optionally) remove any unnecessary spaces,
  4. url-encode it,
  5. and prefix the whole thing with "javascript:".

So, the example would become:

javascript:(function(){document.body.style.backgroundColor%3D%22yellow%22%3B%0Adocument.body.style.color%3D%22red%20!important%22%3B%0A}());

Then you can set the webview's window.location to that string to "run" the bookmarklet.

Here is a page with an automatic script to bookmarklet converter that seems to work.

Upvotes: 3

Related Questions