如何使用 Javascript 删除非自托管网站上的网站图标?

<link rel="shortcut icon" href="https://files.writeas.org/favicon.ico" />

是网站中的代码吗,我无法更改它,我只能更改 CSS 或注入我自己的 Javascript,那么我如何使用 Javascript 获取这部分 HTML 代码并注释掉/覆盖它从而删除它?


阿晨1998
浏览 82回答 2
2回答

阿波罗的战车

如果您无法删除它,您可以使用以下代码更改它(注意:删除可能还不够,因为许多浏览器默认为 /favicon.ico)//const ico_url = document.location.origin + '/favicon.ico'const ico_url = 'https://api.adorable.io/avatar/256/your_icon.png'let head = document.getElementsByTagName('head')[0]console.dir(head)var link;let links = head.getElementsByTagName('link')for(let i=0; i<links.length; i++) {&nbsp; &nbsp;if (links[i].rel == 'icon' || links[i].rel == 'shortcut icon') {&nbsp; &nbsp; &nbsp; link = links[i]&nbsp; &nbsp; &nbsp; console.log('old-icon: '+link.href)&nbsp; &nbsp; &nbsp; link.href = ico_url&nbsp; &nbsp; &nbsp; console.log('new-icon: '+link.href)&nbsp;&nbsp; &nbsp;}}if (typeof(link) == 'undefined') {&nbsp;console.log('creating favicon link !')&nbsp;link = document.createElement('link')&nbsp;link.setAttribute('rel','icon')&nbsp;link.setAttribute('type','image/png')&nbsp;link.setAttribute('href',ico_url) // new favicon ...&nbsp;document.getElementsByTagName('head')[0].appendChild(link)}console.log(link.href)

喵喵时光机

也许你可以尝试更换 head 标签...let ico_url = 'https://api.adorable.io/avatar/256/head_icon.png'&nbsp;var head = document.createElement("head");&nbsp;link = document.createElement('link')&nbsp;link.setAttribute('rel','icon')&nbsp;link.setAttribute('type','image/png')&nbsp;link.setAttribute('href',ico_url) // new favicon ...&nbsp;head.appendChild(link)&nbsp;const html = document.getElementsByTagName('html')[0]&nbsp;html.appendChild(head)&nbsp;html.replaceChild(head,document.getElementsByTagName('head')[0])console.dir(head)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5