Writing Scripts For Facebook

Written by sizzlemctwizzle — Last update Aug 27, 2010

7 points

Description

Writing scripts for Facebook isn't as simple as writing scripts for other sites because Facebook uses Ajax to load pages, making @includes and @excludes useless. I've been using a work around in my scripts along time and now I'm going to share what I've learned with other scriptwrights to make Facebook Greasemonkey friendly once again.

Instructions

The code needed to run your scripts in Facebook must be included via @require and all your code must be wrapped in a function named fbPageChanged. You need to make sure to @include http://*.facebook.com/*

Below is sample script that will only execute on http://*.facebook.com/home.php*
// ==UserScript==
// @name          Facebook Script
// @description   Make any script work on Facebook
// @require       http://userscripts.org/scripts/source/84596.user.js?
// @include       http://*.facebook.com/*
// ==/UserScript==

function fbPageChanged() {
     if (GM_testUrl(['http://*.facebook.com/home.php*'])) {
		// All your code goes here
     }
}

Using GM_testUrl

GM_testUrl duplicates the url matching capabilities of Greasemonkey. The first argument is an array of include urls and the second optional argument is an array of exclude urls. So for example:
if (GM_testUrl(["http://*.google.com/*", "http://*.facebook.com/*"], ["http://*.facebook.com/home.php?*"])) {
  // This is equal to:
  // @include http://*.google.com/*
  // @include http://*.facebook.com/*
  // @exclude http://*.facebook.com/home.php?*
}