Detect when new tweets are loaded using jQuery?

2019-06-04 01:22发布

You know how when you scroll to the bottom of a profile page (I'm talking about a user's personal page, not the timeline), new tweets are loaded automatically. I'm writing a UserScript in which I want to execute a function every time those new tweets are loaded.

But I can't figure out a way to detect this new tweets loaded event. I assume its an AJAX request, right? So I tried the below two functions but to no avail.

$(document).ajaxComplete(function() {
    alert("Complete! New tweets loaded!");
});

$(document).ajaxSuccess(function() {
  alert("Success! New tweets loaded!");
});

Here's what I have so far. This works when the page is loaded at first. But it doesn't affect the tweets loaded after you scroll down.

// ==UserScript==

// @name            CoolScript
// @include         https://twitter.com/IJNanayakkara
// @include         https://twitter.com/IJNanayakkara/status/*
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @require         https://gist.github.com/raw/2625891/waitForKeyElements.js
// @version         1.0
// @license         GPL v3 or any later version (http://www.gnu.org/copyleft/gpl.html)
// @grant           GM_addStyle

// ==/UserScript==

$.each($('p.js-tweet-text'), function() {
    $(this).prepend("Brought to you by ");
});

How can I detect loading new tweets from jQuery?


Edit: I noticed another issue. The script doesn't run when you navigate to the page. I actually have to refresh the page. I searched and found this answer. I imported that .js file to the script but I don't know which element I should actually wait for.

How can I make the script run without manual refreshing?

1条回答
Luminary・发光体
2楼-- · 2019-06-04 02:12

If, your code like this:

$.each($('p.js-tweet-text'), function() {
    $(this).prepend("Brought to you by ");
});

works on the static bits of the page, or from the command console, then it translates into this waitForKeyElements code:

waitForKeyElements ("p.js-tweet-text", prependToTweet);

function prependToTweet (jNode) {
    jNode.prepend("Brought to you by ");
}

Simple: The selector stays the same, and the .each() code ports directly, except that $(this) is replaced by jNode.


waitForKeyElements handles the AJAXed elements automatically (works on scroll-down and without needing refresh).

查看更多
登录 后发表回答