开发者

Interacting with DOM for AJAX webpages?

hey guys, I'm not experienced with developing extensions, but I'm doing it to learn. I'd like to make an extension that blocks only cer开发者_如何学Pythontain twitter icons. By looking through this tutorial I have figured out a lot. I am able to the tweets from the DOM, check for the username, and disable the display of that image with JavaScript.

I got this far by creating a fake page, let's call it twitter.html, that looks a little like this:

<html>
    <div class="stream-item" data-item-type="tweet">
        <div class="tweet-image">
            <img src="abc.jpg" data-user-id="1234">
        </div>
    </div>

.....

<script src="utility.js"></script>
<script type="text/javascript">
var tweets = getElementsByClass("tweet");
for (var i =  0; i < tweets.length; i++) {
    var tweet = tweets[i];
    var name = tweet.getAttribute("data-screen-name");
    if (name.toLowerCase() == 'some-username'.toLowerCase()) {
        var icon = tweet.getElementsByTagName("img")[0];
        icon.style.display='none';
    }
}

</script>

</html>

So hiding the images isn't the problem, but getting the coe to run at the right time is. I'm using Safari extension builder allows me to supply a main page, as well as before-load and after-load js files. However, the page load is "finished" before any tweets get loaded due to the AJAX stuff the real twitter.com uses.

How do I get my js code to run after tweets are loaded?


You should listen to the DOMNodeInserted, which is called... well, every time a DOM Node is Inserted :) Once received, check if the node is of a type that interests you, and proceed from there.

I've took the liberty of modifying your code to accommodate the changes. I've successfully tested this in Chrome.

window.addEventListener("DOMNodeInserted",
    function(event){ 
        var streamItem = event.target;
        if (streamItem == null)
            return;

        if (streamItem.getAttribute('class') != 'stream-item')
            return;

        var tweet = streamItem.getElementsByClassName("tweet",streamItem)[0];
        var name = tweet.getAttribute("data-screen-name");
        if (name.toLowerCase() == 'some-username'.toLowerCase()) 
        {
            var icon = tweet.getElementsByTagName("img")[0];
            icon.style.display='none';
        }
    }, 
    false);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜