使用Google Apps脚本搜索无结果

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Google Apps脚本搜索无结果相关的知识,希望对你有一定的参考价值。

我是在Google Apps脚本中编写的,目的是允许我在Google文档中为youtube打开弹出播放器。其他文件运行正常,但这不行

问题是搜索引擎和用户界面似乎可以正常工作,但是无论等待多长时间,搜索都不会得到结果。如果有人能指出我的错误并告诉我如何解决,那就太好了。

function embed(cacheKey, resourceId, resourceType) {

  const progress = document.querySelector("#progress");
  progress.style.display = "block";

  console.log(cacheKey, resourceId, resourceType);

  var text;

  let checked = document.querySelector('input[type="radio"]:checked').value;

  if (checked === 'string') {
    text = document.querySelector('input[name="link-text"]').value;
  }

  let prefs = {
    "type": checked,
    "string": text
  };

  google.script.run.withSuccessHandler(function(data) {

    if (data.success) {
      document.querySelector('#result').innerText = "Video linked!";
      setTimeout(function() {
        document.querySelector('#result').innerText = "";
      }, 3000);
    }

    if (data.type === "copy" && data.url) {
      navigator.permissions.query({
        name: "clipboard-write"
      }).then(result => {
        if (result.state == "granted" || result.state == "prompt") {
          navigator.clipboard.writeText(data.url);
          alert('URL copied to clipboard');
        }
      });
    }

    progress.style.display = "none";

  }).DTApi('DT', 'embed', cacheKey, prefs, resourceId, resourceType);

}

function previewEmbed(cacheKey, resourceId, resourceType) {

  const progress = document.querySelector("#progress");
  progress.style.display = "block";

  console.log(cacheKey, resourceId, resourceType);
  google.script.run.withSuccessHandler(function(result) {

    let container = document.querySelector("#preview");

    let data = JSON.parse(result);

    console.log(data)

    console.log('Trying to preview: ' + Object.keys(data))

    let settings = function(id, title) {

      const template = "<div class='settings'> 
                             <h2>Settings</h2> 
                             <p>How do you want to link your video?</p> 
                             <input type='radio' id='copy-radio' name='embed-type' value='copy' /><label for='copy-radio'>Copy link to clipboard</label/> 
                             <br /> 
                             <input type='radio' id='thumbnail-radio' name='embed-type' value='thumbnail' /><label for='thumbnail-radio'>Thumbnail</label> 
                             <br /> 
                             <input type='radio' id='toggle' name='embed-type' value='string' /><label for='toggle'>Text</label> 
                             <input type='text' id='link-text' name='link-text' value='" + title + "' /> 
                             <div id='settings-action'> 
                             <button class='action' onclick='embed(this.parentNode.parentNode.parentNode.dataset.cachekey, this.parentNode.parentNode.parentNode.dataset.resourceid, this.parentNode.parentNode.parentNode.dataset.resourcetype)'>Get Video</button> 
                             <button onclick='this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode)'>Close</button> 
                             <div id='result'></div> 
                             </div>
                           </div>";

      return template;

    }

    let previewContainer = document.createElement('div');
    previewContainer.setAttribute('class', 'preview-container');
    previewContainer.dataset.resourceid = data.resourceId;
    previewContainer.dataset.resourcetype = data.resourceType;
    previewContainer.dataset.cachekey = data.cacheKey;
    if (data.resourceType === "channel") {
      previewContainer.innerhtml = '<img src="' + data.preview.high.url + '" />';
    } else {
      previewContainer.innerHTML = data.preview.items[0].player.embedHtml;
    }
    container.appendChild(previewContainer);

    previewContainer.insertAdjacentHTML('beforeend', settings(data.id, data.title));

    progress.style.display = "none";

    window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });

  }).DTApi('DT', 'preview', cacheKey, resourceId, resourceType);

}

function search(page, key) {

  const progress = document.querySelector("#progress");
  progress.style.display = "block";
  // If there's a page token, set it
  var pageToken = page || "";
  var key = key || "";

  let term = document.querySelector('#search-input').value;
  let checked = document.querySelectorAll('input[name="queryArg"]:checked');
  let prev = document.querySelector("#prev");
  let next = document.querySelector("#next");
  let total = document.querySelector("#total-results");

  // Get the checked search types
  let args = {};
  args.types = [];

  // TODO: Validate that there is at least _one_ checked box
  // Default to videos
  checked.forEach(function(el) {
    args.types.push(el.value);
  });

  args.pageToken = page;
  args.key = key;

  const container = document.querySelector('#search-result');
  container.innerText = ('Searching...');
  google.script.run.withSuccessHandler(function(result) {
    container.innerText = '';
    let data = JSON.parse(result);

    console.log(data.data.length);

    if (data.data.length === 0) {
      container.insertAdjacentHTML('beforeend', '<p>No videos found in your search! Try another search term.</p>');
    }

    let videoContainers = [];

    for (var i = 0; i < data.data.length; i++) {
      videoContainers.push(data.data.splice(0, 10))
    }

    console.log(videoContainers);

    videoContainers.forEach(function(items) {
      items.forEach(function(vid) {
        container.insertAdjacentHTML('beforeend', vid);
      });
    });

    if (data.nextPage == undefined) {
      next.disabled = true;
    } else {
      next.disabled = false;
      next.dataset.page = data.nextPage;
      next.dataset.cachekey = data.nextKey;
    }

    if (data.prevPage == undefined) {
      prev.disabled = true;
    } else {
      prev.disabled = false;
      prev.dataset.page = data.prevPage;
      prev.dataset.cachekey = data.prevKey;
    }

    document.querySelector('#pagination').style.display = 'block';
    progress.style.display = "none";
  }).DTApi('DT', 'search', term, args);
}

function getPage(el) {

  let page = el.dataset.page;
  let key = el.dataset.cachekey;
  search(page, key)

}

function paginate(array, page) {

  return array.slice(page * 10, 10)

}

$("#doc").click(function() {
  google.script.run.withSuccessHandler(showFrames).getVideos();
})

$("#comments").click(function() {
  google.script.run.withSuccessHandler(showFrames).getCommentData();
});

function showFrames(frames) {
  $("#embed").empty();
  console.log(frames.length);
  for (var i = 0; i < frames.length; i++) {
    $("#embed").append("<iframe src='https://youtube.com/embed/" + frames[i] + "' width='100%' height='480' frameborder='0' allowfullscreen></iframe>");
  }
}
#progress {
  display: none;
  position: absolute;
  right: 70px;
  top: -5.5px;
}

.search {
  width: 80%;
  margin: 0 auto;
  position: relative;
}

.search>input[type="text"] {
  width: 60%;
  margin-right: 10px;
}

.search>#search-args {
  width: 60%;
}

#search-result {
  margin-top: 15px;
  min-height: 400px;
  display: flex;
  display: -webkit-flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: space-evenly;
  align-items: center;
  align-content: center;
}

#search-result>div {
  transition: box-shadow ease-in-out 0.25s;
  width: 300px;
  height: 180px
}

#search-result>.video-container:hover {
  box-shadow: 0 0 5px blue;
  cursor: pointer;
}

#pagination {
  display: none;
  text-align: right;
  margin-right: 20px;
}

#preview {
  margin: 15px auto 0;
}

.settings {
  display: inline-block;
  vertical-align: middle;
  width: 35%;
  position: relative;
}

#result {
  display: inline-block;
  margin-left: 15px;
}

#preview img {
  width: 45%;
  height: auto;
}

#preview iframe,
img {
  vertical-align: middle;
}

#preview iframe+.settings {
  margin-left: 30px;
}

#preview img+.settings {
  margin-left: 30px;
}

.settings>label {
  line-height: 36px;
}

#link-text {
  visibility: hidden;
  font-size: 18px;
  margin-bottom: 15px;
  margin-left: 15px;
  width: 60%;
}

#toggle:checked~#link-text {
  visibility: visible;
}

.settings>button {
  display: block;
  margin-bottom: 15px;
}

.video-container {
  background-position: center center;
  background-size: cover;
  position: relative;
  flex: 0 0 auto;
  margin: 5px;
}

.type-icon {
  display: block;
  position: absolute;
  bottom: 10px;
  right: 10px;
  height: 32px;
  width: 32px;
}

.action-container {
  display: block;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  height: 65px;
  background-color: rgba(250, 250, 250, 0.75);
  width: 100%;
  text-align: center;
  opacity: 0;
  transition: all ease-in-out 0.5s;
}

.action-container>span {
  padding: 5px;
  line-height: 65px;
  font-size: 24px;
}

span:hover {
  cursor: pointer;
  transition: all ease-in-out 0.15s;
}

.video-container:hover>.action-container {
  opacity: 1;
}

#embed {
  width: 100%;
  font-family: sans-serif;
}

#srcSelect {
  width: 100%;
  margin-bottom: 10px;
}

#srcSelect span {
  display: inline-block;
  margin-right: 15px;
  color: rgba(255, 255, 255, 1);
  background-color: rgba(0, 0, 255, 0.8);
  cursor: pointer;
  border-radius: 3px;
  border: 1px solid rgba(0, 0, 180, 0.8);
  padding: 12px;
}

#srcSelect span:hover {
  color: rgba(0, 0, 180, 1);
  background-color: rgba(255, 255, 255, 0.8);
}
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">

<div class="search">
  <input type="text" id="search-input" value="" />
  <button id="search-btn" class="action" onclick="search(null)">Search</button>
  <button onclick="document.querySelector('#search-result').innerHTML = ''">Clear</button>
  <svg id="progress" version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="40px" height="40px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve">
      <path opacity="0.2" fill="#00d" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946
        s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634
        c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/>
      <path fill="#00d" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0
        C22.32,8.481,24.301,9.057,26.013,10.047z">
      <animateTransform attributeType="xml"
        attributeName="transform"
        type="rotate"
        from="0 20 20"
        to="360 20 20"
        dur="0.5s"
        repeatCount="indefinite"/>
      </path>
    </svg>
  <div id="search-args">
    <label><input type="checkbox" name="queryArg" value="video" checked="checked"/>Videos</label>
    <label><input type="checkbox" name="queryArg" value="channel" />Channels</label>
    <label><input type="checkbox" name="queryArg" value="playlist" />Playlists</label>
  </div>
</div>
<div id="preview"></div>
<div id="pagination">
  <button id="prev" data-page="" onclick="getPage(this)">Previous</button>
  <button id="next" data-page="" onclick="getPage(this)">Next</button>
</div>
<div id="search-result"></div>
我收到的错误是:“未捕获的参考错误:未定义google”,该错误表示该问题发生在第360行内。我从原始编辑器逐行复制了整个ass代码,其中360行是:
        } else {

我该怎么办?在过去的3天里,我一直坚持不懈地检查代码,除了没有发现搜索结果外,没有发现任何错误的证据。我确实为此感到迷this,需要编码骑兵。

答案

正如用户在评论中所说,当您使用Apps脚本[1]时,google对象会自动导入html文件中。您需要删除以下行:<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=..." async defer></script>,这会导致错误,如其他问题[2]所述。

[1] https://developers.google.com/apps-script/guides/html/reference/run

[2] Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

以上是关于使用Google Apps脚本搜索无结果的主要内容,如果未能解决你的问题,请参考以下文章

使用 Google Apps 脚本自动将标签移动/应用到 Gmail

Google Apps 脚本多个自动填充

使用 Google Apps 脚本和 Twitter API 搜索 Twitter 句柄 - 不起作用

Google Apps脚本未遍历所有文件

使用Google Apps脚本查找所有文件夹(和子文件夹)中的文档/幻灯片/表格

使用 Google AppS 脚本将 .csv 文件转换为 .xls