![見出し画像](https://assets.st-note.com/production/uploads/images/129935669/rectangle_large_type_2_209933995394eb8657aa04b3d3751b95.png?width=800)
TwitterのリストTLでミュートを疑似実現するChrome拡張機能(改善版)
前回のコレを少し直したもののコードを掲載。
今回は非表示対象を別のファイルから読み出すように変更。
manifest.json
{
"manifest_version": 3,
"name": "指定した垢をリストTLから消したり",
"version": "1.35",
"permissions": ["tabs", "scripting"],
"background": {
"service_worker": "background.js"
},
"action": {},
"host_permissions": [
"https://twitter.com/i/lists/0000000000"
],
"web_accessible_resources": [
{
"resources": ["mute_list.txt"],
"matches": ["<all_urls>"]
}
]
}
"web_accessible_resources":
ここで呼び出すファイルを指定する。
ファイルだけ指定すれば良いような説明も見かけたけど実際にはmatchesも指定しないとエラーになって動かなかった。
background.js
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (tab.url.indexOf('https://twitter.com/i/lists/0000000000') > -1) {
chrome.scripting.executeScript({
target: {
tabId: tab.id
},
files: ['content.js'],
});
}
});
これは特に変更がないよ。
mute_list.txt
@rikyou_moe
@rikyou_moe2
これを読み込んで非表示の対象にするよ。
1行ごとに1条件と判断。@~を指定すれば対象アカウントを擬似ミュートできる。
content.js
// ミュートリストを読み込む
function fetchMuteList() {
var filePath = chrome.runtime.getURL("mute_list.txt");
return fetch(filePath)
.then(response => {
if (!response.ok) {
throw new Error('ファイルの読み込みに失敗しました。');
}
return response.text();
})
.then(data => {
var lines = data.split('\n');
return lines.map(line => line.trim()).filter(line => line !== ''); // 各行をtrimし、空行を無視
})
.catch(error => {
console.error('ファイルの読み込みエラー:', error);
return []; // エラー時に空の配列を返す
});
}
// ミュート&強調処理
function muteTweet() {
var show_more = 'ポストをさらに表示';
fetchMuteList().then(mutes => {
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.addedNodes) {
mutation.addedNodes.forEach(function (node) {
for (var i = 0; i < mutes.length; i++) {
if (node.nodeType === 1 && node.matches('div[data-testid="cellInnerDiv"]') && node.textContent.includes(mutes[i])) {
node.style.display = 'none';
console.log('非表示になったツイート:', mutes[i]);
}
}
if (node.nodeType === 1 && node.matches('div[data-testid="cellInnerDiv"]') && node.textContent.includes(show_more)) {
node.style.backgroundColor = 'red';
}
});
}
});
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
muteTweet();
大きな変更点はリストからミュートワードを読み込むようにした点。
現実的な話としてミュートワードの追加削除のたびにソースコードの配列変数を書き換えるのは ちょっと、、、、という感じなので。
今回はここまで。
あとやるとしたらミュートリストの追加削除の処理自体を実装するくらい?
この記事が気に入ったらサポートをしてみませんか?