Why does greasemonkey not detect some facebook page changes?

I tried to make the user.js to / messages page on facebook, but it looks like greasemonkey doesn't notice when the navigation changes from / to / messages. This also happens on other internal pages. At first I thought it was caused by AJAX navigation, but the url is changing (not the hash part), so this is normal navigation, right?

This is the test page I used:

// ==UserScript==
// @name           Test
// @namespace      none
// @description    just an alert when page changes
// @include        http*://www.facebook.com/*
// ==/UserScript==

alert(location.href);

How to detect page changes?


Firefox Version: 6.0.2

Greasemonkey Version: 0.9.11

+5
source share
3 answers

, , Firefox 4+, Facebook API HTML5. API history.pushState(), . , , , , , ajax, .

, pushState() :

(function (old) {
    window.history.pushState = function () {
        old.apply(window.history, arguments);
        alert(window.location.href);
    }
})(window.history.pushState); 

API https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history.

+8

DOMNodeInserted , /messages :

// ==UserScript==
// ...
// @include https://www.facebook.com/*
// ...
// ==/UserScript==

var url = document.location.toString();
function scriptBody(){
   if (!url.match(/facebook.com\/messages/)) return;
   // ...
   // do stuff
   // ...
});

scriptBody(); // run on initial page load

document.querySelector('html').addEventListener('DOMNodeInserted', function(ev){
  var new_url = document.location.toString();
  if (url == new_url) return; // already checked or processed
  url = new_url;

  scriptBody(); // run when URL changes
});

, "/", "DOMNodeInserted" , , script, , - , , - .

+3

+1 @rampion. , , .

, , , , href:

if (document.addEventListener ){
  document.addEventListener("click", function(event) {
    var targetElement = event.target || event.srcElement;
    // TODO: support deeper search for parent element with a href attribute
    var href = targetElement.getAttribute('href') || targetElement.parentElement.getAttribute('href') ;
    if (href && videoURLRe.test(href)) {
      var target = "";
      if (href.indexOf("/") == 0) {
        target = "https://m.facebook.com" + href
      } else {
        target = href.replace("www.facebook", "m.facebook");
      }
      window.location.assign(target);
    }   
  }, true);
}

. addEventListener, .

For a full script, check out https://greasyfork.org/en/scripts/8176-switch-to-mobile-version-on-facebook-video-page

I could not find a way to reliably detect changes to URLs, regardless of the method used by the website, to change this URL. @ Andy-e's approach seems awesome, but for some reason didn't work for me. Perhaps I could not make the script tag correctly @grant.

0
source

All Articles