How to fix 'addEventListener' not working in Violentmonkey or Tampermonkey Chrome extension?

huangapple go评论58阅读模式
英文:

How to fix 'addEventListener' not working in Violentmonkey or Tampermonkey Chrome extension?

问题

以下是您要翻译的代码部分:

var textbox = document.getElementById("Text");

var button = document.getElementsByClassName("btn")[0];

textbox.addEventListener("input", function() {
  var inputText = textbox.value.trim();
  if (inputText.length === 5) {
    setTimeout(function() {
      button.click();
    }, 100);
  }
});

请注意,这段代码用于在文本框中输入5个字符后自动点击按钮。这段代码在浏览器的开发者控制台中运行正常,但在Greasemonkey/Tampermonkey扩展中不起作用。您想知道如何在Greasemonkey/Tampermonkey Chrome扩展中运行此代码。

英文:

I want a button to be automatically clicked after 0.1 seconds after entering 5 characters in a textbox....

This code works correctly in the console(developer.F12) section of the browser. But I want this code to be executed permanently in the browser by Greasemonkey/Tampermonkey extension.

var textbox = document.getElementById("Text");

var button = document.getElementsByClassName("btn")[0];

textbox.addEventListener("input", function() {
  var inputText = textbox.value.trim();
  if (inputText.length === 5) {
    setTimeout(function() {
      button.click();
    }, 100);
  }
});

But This is not working in Greasemonkey/Tampermonkey Chrome extension....

Please see this picture:

How to fix 'addEventListener' not working in Violentmonkey or Tampermonkey Chrome extension?

How can I run this code in the Greasemonkey/Tampermonkey Chrome extension?


Update:

In response to Alexander Nenashev:

Let me explain what I want to use this code for.
For example, I want the login button to be automatically clicked on every website page in the login section after entering a 5-digit password.
And also these elements are present on the site
I import this code through the browser console of the developer section (F12), it works, but as soon as the page is refreshed, I have to import this code again, and my problem is exactly here. I want this JavaScript code permanently in the background of every site. I want it to be active, and according to my research, the tampermonkey extension seems to do it, but not for me!

How to fix 'addEventListener' not working in Violentmonkey or Tampermonkey Chrome extension?

I put your code in the Tampermonkey extension, but unfortunately I got the same error as before... And we have the elements available on the desired website

答案1

得分: 1

以下是您要求的翻译部分:

Your error's explanation:
document.getElementById("Text"); returns null since there's no such textbox on the page yet when you run your monkey script.
When you run your code in the console the elements are present so you have no problems.

I believe a monkey script runs after DOMContentLoaded. But...
The page could create elements after this (for example loading some chunk of HTML from the backend and inserting into the page). So...
You should watch the page for the needed elements. The simple way is to use setTimeout() to run your code a bit later hoping the elements are here. And possible repeat the process, stopping when the elements are found.

But there's a more elegant approach. In my monkey scripts I use MutationObserver:

// emulate code on the page

document.querySelector('button').addEventListener('click', e => {

  e.target.remove();

  document.querySelector('.container').innerHTML = `
    <input id="Text">
    <button class="btn">Auto click me</button>
    <div class="log"></div>
  `;

  const textbox = document.querySelector('#Text');
  textbox.focus();

  document.querySelector('.btn').addEventListener('click', () => {
    document.querySelector('.log').innerHTML += `<div>${textbox.value.trim()}</div>`;
    textbox.value = '';
  });
  
});

// your code, watch for body mutations and add listeners;

let observer = new MutationObserver(addListener);

/*
  if you have more specific container where to look and 
  it's present on DOMContentLoaded - use here.
*/
observer.observe(document.body, {childList: true, subtree: true});

function addListener(){

  const textbox = document.querySelector('#Text');
  const button = document.querySelector('.btn');

  if(!textbox || !button){
    return; // not on the page yet
  }

  textbox.addEventListener('input', () => {
    textbox.value.trim().length === 5 && setTimeout(() => button.click(), 100);
  });
  
  // stop observing since you've attached the listener
  
  observer.disconnect();
  observer = null;

  // stackoverflow's console.log() mutates DOM so use it after disconnecting
  console.log('the listener has been added');

};

UPDATE

If an event bubbles you can catch it at the document:

// emulate code on the page

document.querySelector('button').addEventListener('click', e => {

  e.target.remove();

  document.querySelector('.container').innerHTML = `
    <input id="Text">
    <button class="btn">Auto click me</button>
    <div class="log"></div>
  `;

  const textbox = document.querySelector('#Text');
  textbox.focus();

  document.querySelector('.btn').addEventListener('click', () => {
    document.querySelector('.log').innerHTML += `<div>${textbox.value.trim()}</div>`;
    textbox.value = '';
  });
  
});

// your code, watch for inputs to change

document.addEventListener('input', e => {

  const button = document.querySelector('.btn');

  e.target.value.trim().length === 5 && setTimeout(() => button.click(), 100);

});

希望这能帮助您!如果您有任何其他问题,请随时提出。

英文:

Your error's explanation:
document.getElementById(&quot;Text&quot;); returns null since there's no such textbox on the page yet when you run your monkey script.
When you run your code in the console the elements are present so you have no problems.

I believe a monkey script runs after DOMContentLoaded. But...
The page could create elements after this (for example loading some chunk of HTML from the backend and inserting into the page). So...
You should watch the page for the needed elements. The simple way is to use setTimeout() to run your code a bit later hoping the elements are here. And possible repeat the process, stopping when the elements are found.

But there's a more elegant approach. In my monkey scripts I use MutationObserver:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// emulate code on the page

document.querySelector(&#39;button&#39;).addEventListener(&#39;click&#39;, e =&gt; {

  e.target.remove();

  document.querySelector(&#39;.container&#39;).innerHTML = `
    &lt;input id=&quot;Text&quot;&gt;
    &lt;button class=&quot;btn&quot;&gt;Auto click me&lt;/button&gt;
    &lt;div class=&quot;log&quot;&gt;&lt;/div&gt;
  `;

  const textbox = document.querySelector(&#39;#Text&#39;);
  textbox.focus();

  document.querySelector(&#39;.btn&#39;).addEventListener(&#39;click&#39;, () =&gt; {
    document.querySelector(&#39;.log&#39;).innerHTML += `&lt;div&gt;${textbox.value.trim()}&lt;/div&gt;`;
    textbox.value = &#39;&#39;;
  });
  
});

// your code, watch for body mutations and add listeners;

let observer = new MutationObserver(addListener);

/*
  if you have more specific container where to look and 
  it&#39;s present on DOMContentLoaded - use here.
*/
observer.observe(document.body, {childList: true, subtree: true});

function addListener(){

  const textbox = document.querySelector(&#39;#Text&#39;);
  const button = document.querySelector(&#39;.btn&#39;);

  if(!textbox || !button){
    return; // not on the page yet
  }

  textbox.addEventListener(&#39;input&#39;, () =&gt; {
    textbox.value.trim().length === 5 &amp;&amp; setTimeout(() =&gt; button.click(), 100);
  });
  
  // stop observing since you&#39;ve attached the listener
  
  observer.disconnect();
  observer = null;

  // stackoverflow&#39;s console.log() mutates DOM so use it after disconnecting
  console.log(&#39;the listener has been added&#39;);

};

<!-- language: lang-html -->

&lt;button&gt;Add elements&lt;/button&gt;
&lt;div class=&quot;container&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

UPDATE

If an event bubbles you can catch it at the document:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// emulate code on the page

document.querySelector(&#39;button&#39;).addEventListener(&#39;click&#39;, e =&gt; {

  e.target.remove();

  document.querySelector(&#39;.container&#39;).innerHTML = `
    &lt;input id=&quot;Text&quot;&gt;
    &lt;button class=&quot;btn&quot;&gt;Auto click me&lt;/button&gt;
    &lt;div class=&quot;log&quot;&gt;&lt;/div&gt;
  `;

  const textbox = document.querySelector(&#39;#Text&#39;);
  textbox.focus();

  document.querySelector(&#39;.btn&#39;).addEventListener(&#39;click&#39;, () =&gt; {
    document.querySelector(&#39;.log&#39;).innerHTML += `&lt;div&gt;${textbox.value.trim()}&lt;/div&gt;`;
    textbox.value = &#39;&#39;;
  });
  
});

// your code, watch for inputs to change

document.addEventListener(&#39;input&#39;, e =&gt; {

  const button = document.querySelector(&#39;.btn&#39;);

  e.target.value.trim().length === 5 &amp;&amp; setTimeout(() =&gt; button.click(), 100);

});

<!-- language: lang-html -->

&lt;button&gt;Add elements&lt;/button&gt;
&lt;div class=&quot;container&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月29日 09:26:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354206.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定