Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

javascript - Chrome Extension which is supposed to run on all Facebook pages only runs when I hit refresh

This is my first hack at writing a Chrome extension. I want it to execute some pretty simple JavaScript every time a Facebook page loads. It's doing everything I want except that for some reason, it only runs my script if I hit the Refresh button. If, e.g. I clicked on the Facebook logo, or I go to a status from my notifications, the script doesn't run... until I click refresh.

Here is my manifest:

{
    "name": "Anti-social Reader",
    "version": "1.0",
    "description": "Defeats 'social reader' apps on Facebook, by letting you just see the news story directly without installing the app.",
    "content_scripts": [
        {
           "matches": ["http://*.facebook.com/*", "https://*.facebook.com/*"],
           "js": ["kill_social_reader.js"],
           "run_at": "document_end",
           "all_frames": true
        }
     ]
}

I need it to wait until document_end because it is modifying the DOM of the loaded page. I'm sure it's something stupid... any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As mtk said, it's because Facebook uses AJAX calls when you click on the home button or whatever. To run your code every time an AJAX call is made, you can hijack XMLHttpRequest. You could add something like this to your content script, so that every time an AJAX request is opened, your code is called. You could add an event listener to wait for the AJAX request to complete before running your code too.

(function(open) {
  XMLHttpRequest.prototype.open = function() {
    // add the function you want to run here
    open.apply(null, arguments);
  };
})(XMLHttpRequest.prototype.open);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...