Answer the question
In order to leave comments, you need to log in
How to do page search using java script in chrome plugin?
Hello everyone, please help, because. I don’t know JS well, the essence is in the following:
I am writing a plugin for chrome that performs a search on the page, hung a handler on the button, but the chrome policy prohibits the use of inline scripts.
this is how it was originally:
<input type="text" id="text-to-find" placeholder="поиск">
<input type="button" value="найти" onclick="FindOnPage('text-to-find'); return false; "/>
onclick="FindOnPage('text-to-find'); return false;
var lastResFind=""; // последний удачный результат
var copy_page=""; // копия страницы в ихсодном виде
function TrimStr(s) {
s = s.replace( /^\s+/g, '');
return s.replace( /\s+$/g, '');
}
function FindOnPage(inputId) {//ищет текст на странице, в параметр передается ID поля для ввода
var obj = window.document.getElementById(inputId);
var textToFind;
if (obj) {
textToFind = TrimStr(obj.value);//обрезаем пробелы
} else {
alert("Введенная фраза не найдена");
return;
}
if (textToFind == "") {
alert("Вы ничего не ввели");
return;
}
if(document.body.innerHTML.indexOf(textToFind)=="-1")
alert("Ничего не найдено, проверьте правильность ввода!");
if(copy_page.length>0)
document.body.innerHTML=copy_page;
else copy_page=document.body.innerHTML;
document.body.innerHTML = document.body.innerHTML.replace(eval("/name="+lastResFind+"/gi")," ");//стираем предыдущие якори для скрола
document.body.innerHTML = document.body.innerHTML.replace(eval("/"+textToFind+"/gi"),"<a name="+textToFind+" style='background:red'>"+textToFind+"</a>"); //Заменяем найденный текст ссылками с якорем;
lastResFind=textToFind; // сохраняем фразу для поиска, чтобы в дальнейшем по ней стереть все ссылки
window.location = '#'+textToFind;//перемещаем скрол к последнему найденному совпадению
document.getElementById('btn-text-to-find').addEventListener('click',FindOnPage('text-to-find'))
Answer the question
In order to leave comments, you need to log in
1 - Remove all onclick from html
2 - Insert a line
document.getElementById('btn-text-to-find').onclick = function(){
FindOnPage('text-to-find');
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question