javascript 脚本标记上的事件侦听器

nnsrf1az  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(99)

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>

这显示了一个错误:
未选中的运行时。lastError:收到响应前消息端口已关闭。

b4qexyjb

b4qexyjb1#

您尝试添加到头的脚本需要一点时间来加载和执行,即使在onload事件之后也是如此,因为它有太多的工作要做。所以你必须把clickFirstSearchResult();调用放在一个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)

相关问题