我正在设计一个 chrome 扩展程序,它将在页面上搜索文本并将其超链接。我在超链接文本时遇到问题
I am designing a chrome extension that will search for text on a page and hyperlink it. I am having trouble hyperlinking the text
这是我现有的 contentScript.js:
const words = document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, td, caption, span, a');
let div = document.createElement('div');
div.id = 'tag';
let text = document.createTextNode('TAG');
for(let i = 0; i < words.length; i++){
if(words[i].innerHTML.includes('COVID-19')|| words[i].innerHTML.includes('covid-19')){
words[i].innerHTML = words[i].innerHTML.replace('COVID-19', 'THIS WORKS');
div.appendChild(text);
}
此代码在大多数网页上成功地将“TEST”替换为“THIS WORKS”。我想用“THIS WORKS”替换“TEST”并将用户定向到给定的 link。你有什么见解吗?感谢所有帮助。
替换功能支持HTML所以您可以进行以下操作
替换:
words[i].innerHTML = words[i].innerHTML.replace('COVID-19', 'THIS WORKS');
使用(将 CDC link 替换为您想要使用的任何 link):
words[i].innerHTML = words[i].innerHTML.replace('COVID-19', '<a href="https://www.cdc.gov/coronavirus/2019-ncov/index.html" target="_blank">THIS WORKS</a>');
祝您的扩展程序好运!
这是我现有的 contentScript.js:
const words = document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, td, caption, span, a');
let div = document.createElement('div');
div.id = 'tag';
let text = document.createTextNode('TAG');
for(let i = 0; i < words.length; i++){
if(words[i].innerHTML.includes('COVID-19')|| words[i].innerHTML.includes('covid-19')){
words[i].innerHTML = words[i].innerHTML.replace('COVID-19', 'THIS WORKS');
div.appendChild(text);
}
此代码在大多数网页上成功地将“TEST”替换为“THIS WORKS”。我想用“THIS WORKS”替换“TEST”并将用户定向到给定的 link。你有什么见解吗?感谢所有帮助。
替换功能支持HTML所以您可以进行以下操作
替换:
words[i].innerHTML = words[i].innerHTML.replace('COVID-19', 'THIS WORKS');
使用(将 CDC link 替换为您想要使用的任何 link):
words[i].innerHTML = words[i].innerHTML.replace('COVID-19', '<a href="https://www.cdc.gov/coronavirus/2019-ncov/index.html" target="_blank">THIS WORKS</a>');
祝您的扩展程序好运!