简体   繁体   English

如何使用 JavaScript 创建一个 Chrome 扩展来隐藏或删除页面元素?

[英]How to create a Chrome Extension to Hide or Remove a Page Element using JavaScript?

I am trying to create a Chrome Extension to manipulate the HTML on a page.我正在尝试创建一个Chrome 扩展来操作页面上的 HTML。 The extension should remove or hide some elements from a page when activated.扩展程序应在激活时从页面中删除或隐藏某些元素。

I created a simple manifest.json file:我创建了一个简单的manifest.json文件:

{
  "manifest_version": 2,

  "name": "hide-msgs-ext",
  "version": "0.0.1",
  "description": "Hide msgs extension",

  "content_scripts": [{
    "js": ["content.js"],
    "matches": ["https://website.example.com/*"],
    "run_at":  "document_idle"
  }]

}

and a script content.js , which should remove/hide all my target elements:和一个脚本content.js ,它应该删除/隐藏我的所有目标元素:

var elements = document.querySelectorAll('div.card');
for (var i = 0, l = elements.length; i < l; i++) {
  subElement = elements[i].querySelector(':scope div.card-body');
  if (subElement.firstChild.tagName != 'A') {
    elements[i].style.display = "none";
  }
}

If I execute the above script in the chrome console I am able to hide all the elements I want and no errors are triggered.如果我在 chrome 控制台中执行上述脚本,我可以隐藏我想要的所有元素,并且不会触发任何错误。 However I could not figure it out how to make it work in the extension.但是我不知道如何让它在扩展中工作。

Could someone point me in the right direction?有人能指出我正确的方向吗? Thanks you in advance!提前谢谢你!

It sounds like the content might be created by javascript after the page loads so you need to wait for it to appear.听起来内容可能是在页面加载后由 javascript 创建的,因此您需要等待它出现。 You can wrap your code in a function and execute it after a timeout:您可以将代码包装在一个函数中并在超时后执行它:

function hideCards() {
  var elements = document.querySelectorAll('div.card');
  for (var i = 0, l = elements.length; i < l; i++) {
    subElement = elements[i].querySelector(':scope div.card-body');
    if (subElement.firstChild.tagName != 'A') {
      elements[i].style.display = "none";
    }
  }
}

// execute after a second to give the page time to create the
// elements you want to remove
setTimeout(hideCards, 1000);

If you want it to work throughout the life of the page and be very quick, you could try using MutationObserver .如果您希望它在页面的整个生命周期内都能工作并且非常快,您可以尝试使用MutationObserver This lets you listen for DOM changes.这让您可以监听 DOM 更改。 Here's a sample of how to use that.这是如何使用它的示例。 The 'Add Item' button adds a new item, every other one has the 'remove-me' class. “添加项目”按钮添加一个新项目,每个其他项目都有“删除我”类。 The MutationObserver executes a function that automatically removes any LI nodes added with that class so they don't appear: MutationObserver 执行一个函数,该函数会自动删除任何添加到该类中的 LI 节点,以便它们不会出现:

 const observer = new MutationObserver(function(mutations) { let added = []; for (let i = 0; i < mutations.length; i++) { let m = mutations[i]; for (let j = 0; j < m.addedNodes.length; j++) { let n = m.addedNodes[j]; if (n.tagName === 'LI' && n.classList.contains('remove-me')) { added.push(n); } } } added.forEach(element => element.remove()) }); const config = { subtree: true, childList: true }; observer.observe(document.body, config); let index = 0; document.getElementById('btnAddItem') .addEventListener('click', (event) => { let li = document.createElement('li'); if (index & 1 == 1) li.classList.add('remove-me'); li.innerText = `Item ${index++}`; document.getElementById('myList').appendChild(li); });
 <ol id="myList"> <li>First Item</li> </ol> <button id="btnAddItem">Add Item</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM