Writing your own content-blocker for Safari 9 in El Capitan: 4, write, test, debug…

Well it turns out that you can actually create your own content-blockers for Safari 9 under OS X 10.10 and 10.11 without going through the process of registering as a developer and obtain a signing certificate. However such blockers are of very limited use, as they are automatically removed as soon as you quit Safari!

So if you want to create a test content-blocker before you have a security certificate to make it more enduring (and once your certificate is installed), here is how to do that.

Having installed Safari’s Develop menu (Preferences, Advanced, check Show Develop menu in menu bar), open that menu and select the Show Extension Builder command. The Extension Builder will then open, showing no extensions. Click on the + tool at the foot of the left-hand pane to create your new content-blocker extension from the popup menu there. You will then be prompted to save the extension source folder.

The new extension next requires a display name, and other information, and a Bundle Identifier in reverse domain format (e.g. com.mysite.extensionname). Having completed those, you should set the Website Access level to All, including Secure Pages.

saf9contentblock1If you have not already done so, create your content-blocker and save it to a JSON text file, with the extension .json, and move that into the extension source folder which Extension Builder has just created for you. Once that is done, you should be able to select that file as the Content Blocker (Content Blocker File: popup). Check that all is set correctly, and click on the Install button at the top right.

saf9contentblock2You will see a warning that your content-blocker will only work until you quit Safari, and then be prompted for your admin password to actually install the blocker.

Next test your blocker out, by trying to access sites which should be blocked, and those which should not be. Because Safari (actually WebKit on behalf of Safari) compiles content-blocker files into byte code, you will not be able to re-edit the JSON source and expect the blocker to be automatically updated. One way to work around this is to duplicate the JSON source file and increment its number, then switch Extension Builder to use the new JSON source, and Install again.

Although this is not as slick as the traditional edit-compile-test-debug workflow of normal software development, it should still be fairly quick in use. Remember that the moment that you quit Safari your blocker will be trashed, unless you have signed it using the right Apple certificate.

Happy developing!