2

I am making a chrome extension that interacts with pages loaded from YouTube.com. I want to reorder the related videos from largest to smallest on the page, but my content script has to talk to the background page to get some information first. My content script starts the sorting by the following event:

content_script.js:

$(document).ready(function() {
    chrome.runtime.sendMessage({message: "getRecentSortType"}, function(response) {
        PerformSortAction(response.sortType);
    });
});

The background.js script listens, and executes code based off the request:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if(request.message === "getRecentSortType")
    {
        var recentSortType = localStorage.getItem("sortType");
        if(recentSortType === null)
        {
            recentSortType = "sortByViews";
        }

        sendResponse({"sortType": recentSortType});
    }
});

When I run this when reloading the page that I'm on, all of this works fine. However, when I click a related video in YouTube, then the $(document).ready() event doesn't get fired in the content script. If I refresh that page again, then it works.

Can someone explain to me what is going on? I really would prefer to have some event in the content script fire for when a page is done loading.

Right now I have my background.js script listening with the chrome.tabs.onUpdated event, and then sending a message to my content script, but the onUpdated event occurs more than once per page load, messing up the messaging.

GabeMeister
  • 1,668
  • 4
  • 22
  • 28
  • 1
    When you go to a related video, Youtube is not loading a new page... it's doing an ajax request to load the new video. So the document that was already ready is still ready. – Hamza Kubba Apr 23 '15 at 07:38
  • So you basically want to figure out how to listen to that ajax event completing... there are many possibilities, it depends on how Youtube does that. – Hamza Kubba Apr 23 '15 at 07:38
  • Or you can check the list of related videos every half second and do this if the list has changed or something along those lines. – Hamza Kubba Apr 23 '15 at 07:39

1 Answers1

-1

You have to use Jquery .on() method to bind event.

Harmeet Singh
  • 144
  • 1
  • 8