복붙노트

[JQUERY] 추가 기능에서 Google 문서를 폴링하는 방법

JQUERY

추가 기능에서 Google 문서를 폴링하는 방법

해결법


  1. 1.폴링은 당신의 HTML 코드에서 수행되는 추가 기능의 사용자 인터페이스, google.script.run를 사용하여 서버 측 애플리케이션 스크립트 기능을 통해 호출.

    폴링은 당신의 HTML 코드에서 수행되는 추가 기능의 사용자 인터페이스, google.script.run를 사용하여 서버 측 애플리케이션 스크립트 기능을 통해 호출.

    사용 jQuery를이를 단순화하고, 우리는 심지어 jQuery를, 간단한 폴링 예에서 답변을 시작할 수 있습니다.

    function doPoll(){
        $.post('ajax/test.html', function(data) {
            alert(data);  // process results here
            setTimeout(doPoll,5000);
        });
    }
    

    우리는 가스 등가물와 아약스 호출을 대체 할 경우 기본적인 아이디어는, Google 애플리케이션 스크립트에 대한 작업을 수행 할 수 있습니다.

    다음은 HTML 파일에 사용할 것이라고 폴 기능의 골격이다 :

      /**
       * On document load, assign click handlers to button(s), add
       * elements that should start hidden (avoids "flashing"), and
       * start polling for document updates.
       */
      $(function() {
        // assign click handler(s)
    
        // Add elements that should start hidden
    
        // Start polling for updates
        poll();
      });
    
      /**
       * Poll a server-side function 'serverFunction' at the given interval 
       * and update DOM elements with results. 
       *
       * @param {Number} interval   (optional) Time in ms between polls.
       *                            Default is 2s (2000ms)
       */
      function poll(interval){
        interval = interval || 2000;
        setTimeout(function(){
          google.script.run
           .withSuccessHandler(
             function(results) {
               $('#some-element').updateWith(results);
               //Setup the next poll recursively
               poll(interval);
             })
           .withFailureHandler(
             function(msg, element) {
               showError(msg, $('#button-bar'));
               element.disabled = false;
             })
           .serverFunction();
        }, interval);
      };
    

    이는 구글 문서에 사용자의 동작을 감지하는 서버 측 Google 애플리케이션 스크립트 함수를 호출 jQuery를 폴링 기술의 데모입니다. 그것은 아무것도 유용하지 않습니다 있지만 일반적으로는 버튼을 통해 인스턴스 상황에 예민한 제어, 문서의 사용자의 활동과 국가의 지식을 필요로 몇 가지를 전시한다.

    같은 원칙이 스프레드 시트, 또는 독립 실행 형 가스 웹 응용 프로그램에 적용 할 수 있습니다.

    이 문제의 UI 앱의 예와 같이,이 기술은 적어도 사용자 인터페이스와 작업, 실행 시간 제한을 해결하기 위해 사용될 수있다.

    이 코드는 예에 따라 추가 기능에서 구글의 5 분 퀵 스타트를 작성합니다. 빠른 시작 아래 대신 그 코드를 사용하여, 그 가이드에서 지침을 따르십시오.

    /**
     * Creates a menu entry in the Google Docs UI when the document is opened.
     *
     * @param {object} e The event parameter for a simple onOpen trigger. To
     *     determine which authorization mode (ScriptApp.AuthMode) the trigger is
     *     running in, inspect e.authMode.
     */
    function onOpen(e) {
      DocumentApp.getUi().createAddonMenu()
          .addItem('Start', 'showSidebar')
          .addToUi();
    }
    
    /**
     * Runs when the add-on is installed.
     *
     * @param {object} e The event parameter for a simple onInstall trigger. To
     *     determine which authorization mode (ScriptApp.AuthMode) the trigger is
     *     running in, inspect e.authMode. (In practice, onInstall triggers always
     *     run in AuthMode.FULL, but onOpen triggers may be AuthMode.LIMITED or
     *     AuthMode.NONE.)
     */
    function onInstall(e) {
      onOpen(e);
    }
    
    /**
     * Opens a sidebar in the document containing the add-on's user interface.
     */
    function showSidebar() {
      var ui = HtmlService.createHtmlOutputFromFile('Sidebar')
          .setTitle('Document Poller');
      DocumentApp.getUi().showSidebar(ui);
    }
    
    /**
     * Check if there is a current text selection.
     *
     * @return {boolean}  'true' if any document text is selected
     */
    function checkSelection() {
      return {isSelection : !!(DocumentApp.getActiveDocument().getSelection()),
              cursorWord : getCursorWord()};
    }
    
    /**
     * Gets the text the user has selected. If there is no selection,
     * this function displays an error message.
     *
     * @return {Array.<string>} The selected text.
     */
    function getSelectedText() {
      var selection = DocumentApp.getActiveDocument().getSelection();
      if (selection) {
        var text = [];
        var elements = selection.getSelectedElements();
        for (var i = 0; i < elements.length; i++) {
          if (elements[i].isPartial()) {
            var element = elements[i].getElement().asText();
            var startIndex = elements[i].getStartOffset();
            var endIndex = elements[i].getEndOffsetInclusive();
    
            text.push(element.getText().substring(startIndex, endIndex + 1));
          } else {
            var element = elements[i].getElement();
            // Only translate elements that can be edited as text; skip images and
            // other non-text elements.
            if (element.editAsText) {
              var elementText = element.asText().getText();
              // This check is necessary to exclude images, which return a blank
              // text element.
              if (elementText != '') {
                text.push(elementText);
              }
            }
          }
        }
        if (text.length == 0) {
          throw 'Please select some text.';
        }
        return text;
      } else {
        throw 'Please select some text.';
      }
    }
    
    /**
     * Returns the word at the current cursor location in the document.
     *
     * @return {string}   The word at cursor location.
     */
    function getCursorWord() {
      var cursor = DocumentApp.getActiveDocument().getCursor();
      var word = "<selection>";
      if (cursor) {
        var offset = cursor.getSurroundingTextOffset();
        var text = cursor.getSurroundingText().getText();
        word = getWordAt(text,offset);
        if (word == "") word = "<whitespace>";
      }
      return word;
    }
    
    /**
     * Returns the word at the index 'pos' in 'str'.
     * From https://stackoverflow.com/questions/5173316/finding-the-word-at-a-position-in-javascript/5174867#5174867
     */
    function getWordAt(str, pos) {
    
      // Perform type conversions.
      str = String(str);
      pos = Number(pos) >>> 0;
    
      // Search for the word's beginning and end.
      var left = str.slice(0, pos + 1).search(/\S+$/),
          right = str.slice(pos).search(/\s/);
    
      // The last word in the string is a special case.
      if (right < 0) {
        return str.slice(left);
      }
    
      // Return the word, using the located bounds to extract it from the string.
      return str.slice(left, right + pos);
    }
    
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
    <!-- The CSS package above applies Google styling to buttons and other elements. -->
    
    
    <div class="sidebar branding-below">
      <form>
        <div class="block" id="button-bar">
          <button class="blue" id="get-selection" disabled="disable">Get selection</button>
        </div>
      </form>
    </div>
    
    <div class="sidebar bottom">
      <img alt="Add-on logo" class="logo" height="27"
          id="logo"
          src="https://www.gravatar.com/avatar/adad1d8ad010a76a83574b1fff4caa46?s=128&d=identicon&r=PG">
      <span class="gray branding-text">by Mogsdad, D.Bingham</span>
    </div>
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script>
      /**
       * On document load, assign click handlers to button(s), add
       * elements that should start hidden (avoids "flashing"), and
       * start polling for document selections.
       */
      $(function() {
        // assign click handler(s)
        $('#get-selection').click(getSelection);
    
    
        // Add elements that should start hidden
        var newdiv1 = $( "<div class='block' id='cursor-word'/>" ).hide(),
            newdiv2 = $( "<div class='block' id='selected-text'/>" ).hide();
        $('#button-bar').after( newdiv1, newdiv2 );
        $('#cursor-word').html('<H2>Word at cursor:</H2><p id="cursor-word-content"></p>');
        $('#selected-text').html('<H2>Selected text:</H2><p id="selected-text-content"></p>');
    
        // Start polling for updates        
        poll();
      });
    
      /**
       * Poll the server-side 'checkSelection' function at the given
       * interval for document selection, and enable or disable the
       * '#get-selection' button.
       *
       * @param {Number} interval   (optional) Time in ms between polls.
       *                            Default is 2s (2000ms)
       */
      function poll(interval){
        interval = interval || 2000;
        setTimeout(function(){
          google.script.run
           .withSuccessHandler(
             function(cursor) {
               if (cursor.isSelection) {
                 // Text has been selected: enable button, hide cursor word.
                 $('#get-selection').attr('disabled', false);
                 $('#cursor-word').hide();
                 // $('#selected-text').show();  // Not so fast - wait until button is clicked.
               }
               else {
                 $('#get-selection').attr('disabled', true);
                 $('#cursor-word').show();
                 $('#selected-text').hide();
               }
               $('#cursor-word-content').text(cursor.cursorWord);
               //Setup the next poll recursively
               poll(interval);
             })
           .withFailureHandler(
             function(msg, element) {
               showError(msg, $('#button-bar'));
               element.disabled = false;
             })
           .checkSelection();
        }, interval);
      };
    
      /**
       * Runs a server-side function to retrieve the currently
       * selected text.
       */
      function getSelection() {
        this.disabled = true;
        $('#error').remove();
        google.script.run
          .withSuccessHandler(
            function(selectedText, element) {
              // Show selected text
              $('#selected-text-content').text(selectedText);
              $('#selected-text').show();
              element.disabled = false;
            })
          .withFailureHandler(
            function(msg, element) {
              showError(msg, $('#button-bar'));
              element.disabled = false;
            })
          .withUserObject(this)
          .getSelectedText();
      }
    
    
      /**
       * Inserts a div that contains an error message after a given element.
       *
       * @param msg The error message to display.
       * @param element The element after which to display the error.
       */
      function showError(msg, element) {
        var div = $('<div id="error" class="error">' + msg + '</div>');
        $(element).after(div);
      }
    </script>
    

    의 setTimeout () 함수는 밀리 초 단위 표현 된 시간 간격을 허용하지만, I는 두 번째 응답이 예상 될 수있는 최적의 것을 실험을 통해 발견 하였다. 따라서, 골격 여론 조사 ()는 기본값으로도 간격 2000ms 있습니다. 상황이 설문 조사주기 사이의 긴 지연을 허용 할 수있는 경우, 설문 조사에에 onLoad ()를 호출, 예를 들어,에 더 큰 가치를 제공 10 초 폴주기에 대한 설문 조사 (10000).

    나는 세포에서 사이드 바의 표시 값을 어떻게해야합니까 시트 예를 들어 볼 수?

  2. from https://stackoverflow.com/questions/24773177/how-to-poll-a-google-doc-from-an-add-on by cc-by-sa and MIT license