【问题标题】:Roll20, Javascript document.querySelector not workingRoll20,Javascript document.querySelector 不工作
【发布时间】:2022-10-01 01:42:01
【问题描述】:

我正在尝试获取一个简单的 chrome 扩展来注入 roll20 的文本区域。我尝试了多种选择相关元素的方法。我知道这是可能的,因为 Beyond20 做到了。不管怎样,所有的尝试都失败了。对象始终返回 null。甚至:

const foo = document.querySelector(\'#textchat-input\');

alert(foo);

我最近的尝试:

索引.html

<div id=\"test\">
<button id=\"myButton\">Press me</button>
</div>
<script src=\"libs/jquery-3.4.1.min.js\" charset=\"UTF-8\"></script>
<script src=\"script.js\"></script>

脚本.js

document.querySelector(\"button#myButton\").addEventListener(\"click\", postToChat);

function postToChat(){

  const message = \"testing\";
  const chatInputElement = document.querySelector(\'#textchat-input textarea\');
  const chatButtonElement = document.querySelector(\'#textchat-input .btn\');
  
   if (chatInputElement && chatButtonElement) {
    const activeText = chatInputElement.value;
    chatInputElement.value = message;
    chatButtonElement.click();
    if (activeText) setTimeout(() => chatInputElement.value = activeText, 10);
  }
  
}
  • document.querySelector(\'#textchat-input\'); 正在寻找 ID 为 \"textchat-input\" 的 DOM 元素。你没有其中之一,所以它返回 null。 (顺便说一句:如果你使用console.log istead of alert,你会发现调试事情要容易得多)
  • 您还尝试从 input 字段中读取输入(因为您正在使用其 value),但 chatButtonElement 应该是它的子元素(基于 #textchat-input .btn选择器)。输入不能包含其他元素。
  • 此外,您正在阅读chatInputElement.value,然后尝试将完全相同的值写回完全相同的位置,但无缘无故地在超时内。
  • chatButtonElement.click() 不会产生任何结果,因为该元素没有附加点击事件。

标签: javascript google-chrome-extension queryselector


【解决方案1】:

我用你的例子整理了一个小提琴:

https://jsfiddle.net/ydx1aog2/1/

document.querySelector("button#myButton").addEventListener("click", postToChat);

function postToChat(){
    console.log('Executing postToChat!');

  const message = "testing";
  const chatInputElement = document.querySelector('#textchat-input textarea');
  const chatButtonElement = document.querySelector('#textchat-input .btn');

  if (chatInputElement && chatButtonElement) {
    const activeText = chatInputElement.value;
    console.log(`activeText: ${activeText}`);
    
    chatInputElement.value = message;
    chatButtonElement.click();
    if (activeText) setTimeout(() => chatInputElement.value = activeText, 500);
  }
  
}
#textchat-input {
  border: 1px solid black;
  padding: 10px;
  margin-bottom: 20px;
}
<div id="textchat-input">
  <textarea></textarea>
  <button class="btn">Example button</button>
</div>

<button id="myButton">Press me</button>

在您的示例中似乎一切正常,尽管我注意到您传递给setTimeout 的时间非常短(只有 10 毫秒),以至于testing 闪烁得如此之快,您可能看不到它。

我将超时时间提高到 500 毫秒,以便更明显地看出文本已更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 2011-07-12
    • 2015-11-15
    相关资源
    最近更新 更多