脚本标签上的事件监听器

问题描述 投票:0回答:1

我创建了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>

这显示错误:

Unchecked runtime.lastError: The message port closed before a response was received.
javascript html jquery dom async-await
1个回答
0
投票

即使在

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

script.onload = function () {
    setTimeout(clickFirstSearchResult, 1000)
};
© www.soinside.com 2019 - 2024. All rights reserved.