你好, 我想删除出现在 YouTube 上的缩略图。我为此使用以下代码。
while (true) {
$("ytd-thumbnail").remove()
}
当我将这段代码粘贴到控制台时,所有缩略图都被删除了。我希望它通过添加扩展在背板上工作。我正在准备的插件代码如下。
manifest.json;
{
"manifest_version": 2,
"name": "test",
"description": "test extension",
"version": "1.0",
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
popup.html
<!doctype html>
<html>
<head>
<title>TEST</title>
<script src="popup.js"></script>
</head>
<body>
<h1>TEST</h1>
<button id="checkPage">Check !</button>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function() {
chrome.tabs.getSelected(null, function(tab) {
d = document;
while (true) {
$("ytd-thumbnail").remove()
}
});
}, false);
}, false);
当我按下 checkPage 按钮时,没有任何反应。但是当我添加控制台时,这段代码有效。问题是什么?提前致谢。
最佳答案
扩展有几个问题:
- 您正在尝试使用 $ 即 jquery,它在您的系统中不可用 popup.js
- 您正在尝试访问属于“ytd-thumbnail”的 dom 元素 到 youtube 页面而不是你的 popup.html。所以,即使你更换 $ 使用 document.querySelector ,您将找不到这些元素。
我创建了一个看起来像这样的工作版本。我没有包含与您相同的 popup.html。
- manifest.json
{
"manifest_version": 2,
"name": "Hello Extensions",
"description" : "Base Level Extension",
"version": "1.0",
"browser_action": {
"default_icon": "hello_extensions.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["background.js"],
"all_frames" : true
}
],
"permissions": [
"activeTab",
"tabs"
]
}
2.popup.js
document.addEventListener('DOMContentLoaded', function()
{
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function()
{
chrome.tabs.query({"active":true}, function (tabs){
chrome.tabs.sendMessage(tabs[0].id, "removeThumbnails", function (response) {
});
});
});
});
单击按钮时,检索事件选项卡并向其发送“removeThumbnails”消息。
3.background.js
chrome.runtime.onMessage.addListener(function(message, callback) {
if (message == "removeThumbnails")
{
var elements = document.querySelectorAll("ytd-thumbnail");
elements.forEach(a => a.parentNode.removeChild(a));
}
});
background.js 是内容脚本,在 youtube 页面中运行。它现在可以访问 youtube 页面中的所有 dom 元素。当我们收到“removeThumbnails”消息时,获取所有 ytd-thumbnail 元素并将它们从页面中删除。
关于javascript - 如何使用 Google Chrome for Youtube 运行扩展程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51694681/