C
C
Cyril2017-05-12 09:07:37
JavaScript
Cyril, 2017-05-12 09:07:37

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; "/>


accordingly, chrome swears at inline scripts: the search script itself:
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;//перемещаем скрол к последнему найденному совпадению


everything works, everything searches, BUT IT DOES NOT WORK IN THE PLUG because it is impossible to inline, I know what can be done as a dynamic handler, something like:

document.getElementById('btn-text-to-find').addEventListener('click',FindOnPage('text-to-find'))


but how to screw it all xzxz, kindly tell me how to make all this work so that there is no JS in pupup.html

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor Zhivagin, 2017-05-12
@Krasnodar_etc

1 - Remove all onclick from html
2 - Insert a line

document.getElementById('btn-text-to-find').onclick = function(){
    FindOnPage('text-to-find');
};

Or a line from the question to the code, for example, immediately after the declaration of variables (on line 3).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question