سؤال

I'm writing a reasonably complex browser extension for Chrome, Firefox & Safari.

In Chrome & Firefox, I can specify which content script are injected into which sites based on URL matching.

Safari doesn't appear to offer any such (fine grained) functionality – they only allow one white/blacklist for all sites.

Is there a way to do this? If not, how can I conditionally load a Javascript file? (bearing in mind I can't add them to the DOM).

I've tried yepnope, but it appends to the DOM.

Note: I don't want to add logic to the actual files, as they are essentially library code that's duplicated across the extensions.

هل كانت مفيدة؟

المحلول

safari.extension.addContentScript and safari.extension.addContentScriptFromURL allow you to programmatically inject scripts. You can use these methods in either your global page, an extension popover, or an extension bar. For both methods, the arguments are:

  • the script to inject (as a string or as a URL, respectively),
  • a whitelist of URL patterns to match pages on which to inject the script,
  • a blacklist to exclude pages, and
  • a boolean for whether to inject the script as an end script (or else as a start script).

See this page in the Safari Extensions Reference for details.

Note that the whitelist and blacklist both use a URL pattern format that is similar (but not identical) to UNIX wildcards and is not nearly so powerful as regular expresssions. This pattern format is described at the bottom of this page.

نصائح أخرى

The accepted answer is correct but it's important to note that you cannot programatically inject scripts into currently open tabs like Chrome and Firefox can. The SafariExtension Class Reference states:

Adding and removing style sheets and scripts. Adding or removing a content style sheet applies to pages immediately. Adding or removing a content script applies only to pages opened or reloaded after that point. Removing a style sheet or a script that is in the Info.plist file removes it only from the current browser session.

Because of this limitation, it's often easier to simply rely on the Scripts attribute in Info.plist instead.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top