脚本标记上的事件侦听器

event listener on script tag

提问人:anurag 提问时间:9/29/2023 最后编辑:isherwoodanurag 更新时间:9/29/2023 访问量:50

问:

我创建了CSE(自定义搜索引擎)

<script async src="https://cse.google.com/cse.js?cx=f2bcbf82e6df34220">
</script>
<div class="gcse-search"></div>

我尝试使用js执行所有内容,因此我创建了此代码

async function clickFirstSearchResult() {
  // Get a reference to the input element by its ID
  var inputElement = document.getElementById("gsc-i-id1");

  // Check if the input element exists on the page
  if (inputElement) {
    // Set the text you want to type into the input element
    var searchText = "newsze99.blogspot.com";

    // Simulate typing by dispatching input events with each character
    for (var i = 0; i < searchText.length; i++) {
      var char = searchText.charAt(i);
      var event = new Event("input", { bubbles: true });
      inputElement.value += char;
      inputElement.dispatchEvent(event);
    }

    // Get a reference to the search button by its class name
    var searchButton = document.querySelector(".gsc-search-button.gsc-search-button-v2");

    // Check if the search button exists on the page
    if (searchButton) {
      // Trigger a click event on the search button
      searchButton.click();
    }

    // Wait for a short period (adjust as needed) to ensure the search results load
    await new Promise(resolve => setTimeout(resolve, 2000)); // Adjust the delay as needed

    // Now, fetch the value (href) inside the first search result link
    var firstSearchResultLink = document.querySelector(".gs-title a");

    // Check if the first search result link exists on the page
    if (firstSearchResultLink) {
      var linkHref = firstSearchResultLink.getAttribute("data-cturl");

      // Open the link in a new tab
      window.open(linkHref, "_blank");
    }
  }
}

// Call the function to start the process
clickFirstSearchResult();

当这个js在浏览器的控制台中执行时,它在搜索框中输入查询,按回车键,然后单击第一个链接,正如我所期望的那样。 但是当我在我的 HTML 代码中使用它时,它不起作用。

我的HTML代码

此 HTML 可能仅适用于实时服务器,因此请在 W3School 上尝试此操作,因为它不适用于我系统中的 HTML 文件

<!DOCTYPE html>
<html>

<head>
  <title>Page Title</title>
</head>

<body>
  <div class="gcse-search"></div>


  <script>
    // Define a function to execute after the initial script loads
    function executeAfterScriptLoad() {
      async function clickFirstSearchResult() {
        // Get a reference to the input element by its ID
        var inputElement = document.getElementById("gsc-i-id1");

        // Check if the input element exists on the page
        if (inputElement) {
          // Set the text you want to type into the input element
          var searchText = "newsze99.blogspot.com";

          // Simulate typing by dispatching input events with each character
          for (var i = 0; i < searchText.length; i++) {
            var char = searchText.charAt(i);
            var event = new Event("input", {
              bubbles: true
            });
            inputElement.value += char;
            inputElement.dispatchEvent(event);
          }

          // Get a reference to the search button by its class name
          var searchButton = document.querySelector(".gsc-search-button.gsc-search-button-v2");

          // Check if the search button exists on the page
          if (searchButton) {
            // Trigger a click event on the search button
            searchButton.click();
          }

          // Wait for a short period (adjust as needed) to ensure the search results load
          await new Promise(resolve => setTimeout(resolve, 2000)); // Adjust the delay as needed

          // Now, fetch the value (href) inside the first search result link
          var firstSearchResultLink = document.querySelector(".gs-title a");

          // Check if the first search result link exists on the page
          if (firstSearchResultLink) {
            var linkHref = firstSearchResultLink.getAttribute("data-cturl");

            // Open the link in a new tab
            window.open(linkHref, "_blank");
          }
        }
      }


      // Create a script element for the provided script
      var script = document.createElement("script");
      script.src = "https://cse.google.com/cse.js?cx=f2bcbf82e6df34220"; // Replace with the actual URL of the provided script
      script.onload = function() {
        // The provided script has finished loading, execute your function
        clickFirstSearchResult();
      };

      // Append the script element to the document
      document.head.appendChild(script);
    }

    // Wait for the page to finish loading
    window.addEventListener("load", executeAfterScriptLoad);
  </script>
</body>

</html>

这显示了一个错误:

未检查的 runtime.lastError:消息端口在收到响应之前关闭。

javascript html jquery dom 异步-await

评论

1赞 Heretic Monkey 9/29/2023
请查看如何提问,尤其是标题为“写一个总结问题的标题”的部分,并相应地编辑问题。

答:

0赞 Arash jahan bakhshan 9/29/2023 #1

您尝试添加到标头的脚本需要一点时间来加载和执行,即使在事件发生之后也是如此,因为它有很多工作要做。 所以你必须把调用放在onloadclickFirstSearchResult();setTimeout

script.onload = function () {
    setTimeout(clickFirstSearchResult, 1000)
};

或者,您也可以每 10 毫秒检查一次 DOM 中的输入。 如果是,请运行脚本:

function waitFor(id, callback){
    var interval;

    function check(){
        if(document.getElementById(id)) {
            clearInteval(interval);
            callback();
        }
    }

    check();
    interval = setInterval(check, 10)
 }

waitFor("gsc-i-id1", clickFirstSearchResult)