Chrome extensions for Facebook — detecting new pages

I wrote a Chrome extension earlier this week to hide Buzzfeed links from my news feed, my groups, and others’ profiles. However, I was having issues detecting when a user had changed pages so I could re-fire my script onto the new DOM. That’s because Facebook updates their pages with AJAX.

Chrome has a tabs library that one can use to check for when a tab’s URL has changed, onUpdated. However, Facebook updates the browser URL before the AJAX call completes. We’ll have to do this another way.

After poking around the Chrome console, I found that Facebook’s AJAX calls to a new page all use the GET parameter ajaxpipe=1 in the URL. So, all I had to do was snipe the HTTP request and re-fire my script on success. It turns out that Chrome’s webRequest library has a great onCompleted library to help us out here. Here’s the code I ended up writing:

chrome.webRequest.onCompleted.addListener(function(details) {
  var url = document.createElement('a');
  url.href = details.url;
  if (url.search && url.search.indexOf('ajaxpipe=1') !== -1) {
    console.log('New page via AJAX.');
    chrome.tabs.executeScript({'file' : 'blocker.js'});
  }
}, {urls : ["*://*.facebook.com/*"]});

Creating a link element was the quickest way for me to parse the GET parameters (url.search) out of the URL. If the link has search parameters and specifically has ajaxpipe=1, we know that Facebook has finished loading the new page, so we can fire off our content script (which here watches the DOM for Buzzfeed links and hides those posts).