更改Chrome扩展程序中的推文文本

时间:2016-12-03 18:00:40

标签: javascript html google-chrome twitter google-chrome-extension

我正在制作一个改变推文文本的Chrome扩展程序 我使用

检索并更改.js文件中的推文文本
var tweets = document.getElementsByClassName('js-tweet-text tweet-text');
for (var i = 0, l = tweets.length; i < l; i++) {
    tweets[i].innerText = 'Some text';
}

页面加载时加载的推文更改为“某些文本”,但是当我向下滚动加载的新推文时不会更改。 如何更改新的推文文字?

编辑: 我尝试添加一个计时器:

var tweets = document.getElementsByClassName('js-tweet-text tweet-text');
var timer = setInterval(changeTexts, 1000);

function changeTexts() {
for (var i = 0, l = tweets.length; i < l; i++) {
    tweets[i].innerText = 'Some Text';
}
}

但是这会加载html上的所有推文,我只想修改新的推文,而不是修改已经修改过的推文。

1 个答案:

答案 0 :(得分:0)

卢克,使用MutationObserver

var root = document.querySelector('#fTweets'),
    tweetBody = document.querySelector('#fTweetBody'),
    sendBtn = document.querySelector('#fSendBtn'),
    
    pushTweet = _ => root.insertAdjacentHTML('beforeend', `<div class='fTweet'>${tweetBody.value}</div>`);
sendBtn.addEventListener('click', e => pushTweet());

// This function changes the new tweet
let editTweet = e => e.innerHTML += '| Edited by me';

// Immediately after loading change downloaded tweets
// Do not forget about the availability of DOM
Array.from(root.children).forEach(e => editTweet(e));

// Create a MutationObserver instance
new MutationObserver(function(mutations) {
  // We process all the changes of the root node
  mutations.forEach(mutation => {
    // If this change units, then send a new node for processing
    // Note: There is no inspection, that to this example, but be sure to check what and where nodes are in real code
    if(mutation.type === 'childList'){
      mutation.addedNodes.forEach(item => editTweet(item));
    }
  });
}).observe(root, {childList: true});
<div id='fTweets'><div class='fTweet'>First tweet...</div></div><hr />
<textarea placeholder='Your tweet...' id='fTweetBody'></textarea><br />
<input type='button' id='fSendBtn' value='Send' />