<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>於是寫下生活筆記</title><link>https://preview.yuslife.cc/tags/google-forms/</link><description>Recent content in Google Forms on 於是寫下生活筆記</description><generator>Hugo -- gohugo.io</generator><language>zh-TW</language><lastBuildDate>Fri, 09 Dec 2022 12:00:00 +0000</lastBuildDate><atom:link href="https://preview.yuslife.cc/tags/google-forms/index.xml" rel="self" type="application/rss+xml"/><item><title>用 Google Sheet + Google App Script 打造網頁計數器</title><link>https://preview.yuslife.cc/coding/google-app-script-article-pageview/</link><pubDate>Fri, 09 Dec 2022 12:00:00 +0000</pubDate><guid>https://preview.yuslife.cc/coding/google-app-script-article-pageview/</guid><description>過去本站無論是全站瀏覽數或是單篇文章的瀏覽數，都是透過 Google Analytics 搭配 Google Sheets 串接提供的，主要是參考前輩 August 大大的文章更改而成，但上述的方法將會在明年 7 月</description><content:encoded><![CDATA[<p>過去本站無論是全站瀏覽數或是單篇文章的瀏覽數，都是透過 Google Analytics 搭配 Google Sheets 串接提供的，主要是參考前輩 August 大大的<a href="https://www.letswrite.tw/ga-spreadsheet-add-on/" title="用 GA Spreadsheet Add-on 製作網站訪客人數功能">文章</a>更改而成，但上述的方法將會在明年 7 月遇到問題—— Google Analytics 將從通用版全面改為 Google Analytics 4（GA4）。</p>
<p>然而目前 GA4 尚未提供與 Google Sheets 搭配串接的官方外掛（非官方大多須付費），因此筆者便將腦筋動到了 Google 的另一項服務—— Google Apps Script（GAS）上，本文將紀錄筆者如何透過 Google Sheets + Google Forms 紀錄本站瀏覽數，並透過 Google Apps Script 串接將瀏覽數顯示在網站上。</p>
<h2 id="整體流程如何運作">整體流程如何運作？</h2>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-01_hu07c21d16551a1ec421e9603ea25331e7_41904_400x0_resize_q75_h2_box_3.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-01_hu07c21d16551a1ec421e9603ea25331e7_41904_600x0_resize_q75_h2_box_3.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-01_hu07c21d16551a1ec421e9603ea25331e7_41904_960x0_resize_q75_h2_box_3.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-01_hu07c21d16551a1ec421e9603ea25331e7_41904_960x0_resize_box_3.png" alt="運作流程圖"
            class="lazy"  title="運作流程圖"  width="960" height="540">
    </picture>
    
    <figcaption>
        <p>運作流程圖</p>
    </figcaption>
    
</figure></p>
<p>首先，我們會先透過 Google Forms 功能，在所有使用者到訪網站時觸發並記錄下來，將結果回傳到與表單連動的 Google Sheets 中。</p>
<p>接下來，在 Google Sheets 中我們將進行簡單的數據整理，以利後續網頁接收資料時使用，在這裡，便是將 Google Sheets 作為一個小型資料庫使用。</p>
<p>最後，我們透過 Google Apps Script 將 Google Sheets 中的資料變身成為 API，並在網站上串接使用，顯示於網頁前端。</p>
<p>就讓我們開始吧！</p>
<h2 id="先建立紀錄用的-google-表單">先建立紀錄用的 Google 表單</h2>
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLScBtEkMNxQJrrIK0kLJHMOUFnPqWv7Dpa7P36J7BLrGszqJuQ/viewform?embedded=true" width="640" height="600" frameborder="0" marginheight="0" marginwidth="0" style="width: 100%;height: auto;aspect-ratio: 16 / 12;">載入中…</iframe>
<p>在這個表單中，我們要紀錄的是使用者進入的網址，並增加計數，紀錄網只是為了後續可以在個別文章頁面上顯示個別瀏覽數，而計數欄位則是方便後續直接加總。</p>
<p>需要注意的是，這兩個欄位在 Google Forms 上的設定，必須選擇「簡答」，且不可設為必填（參考下圖），這是避免後續傳送資料發生錯誤。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-02_hu231a7e0183de13310075b2e84c8b865f_24779_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-02_hu231a7e0183de13310075b2e84c8b865f_24779_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-02_hu231a7e0183de13310075b2e84c8b865f_24779_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-02_hu231a7e0183de13310075b2e84c8b865f_24779_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<p>表單題目設定完成後，點選上方「回覆」分頁，並點選「建立試算表」，後續我們會將這個試算表作為小型資料庫來使用。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-03_hue90d7272d7568ea45156237e30f0d316_25476_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-03_hue90d7272d7568ea45156237e30f0d316_25476_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-03_hue90d7272d7568ea45156237e30f0d316_25476_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-03_hue90d7272d7568ea45156237e30f0d316_25476_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<h2 id="將網頁計數透過-google-form-寫入-google-sheet-吧">將網頁計數透過 Google Form 寫入 Google Sheet 吧</h2>
<p>接下來我們回到網站，要來寫 Code 將資料傳入 Google Sheets 中，這部份將會參考同樣是 August 大大的<a href="https://www.letswrite.tw/custom-google-form/" title="完全客製 Google 表單，美化表單樣式">文章</a>來進行。</p>
<p>事實上，這個方法是透過 Google Forms 回傳到後端的端口作為我們要將資料傳入 Google Sheets 的入口，因此必須取得這份表單的：</p>
<ol>
<li>POST 的 URL</li>
<li>各欄位的 name</li>
</ol>
<h3 id="先來取得-post-的-url-吧">先來取得 POST 的 URL 吧</h3>
<p>取得的方式也很簡單，前往稍早建立完成的表單頁面後（可以點擊右上方的預覽前往），點擊右鍵 → 檢查，即可開啟 DevTools 界面。</p>
<p>在此界面中點選右上方「…」符號並選取搜尋，或按下快捷鍵「crtl+F / cmd+F」，並在搜尋欄位中搜尋「&lt;form」。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-04_hu56e3e2ad37df09365391a0bf4a088392_115148_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-04_hu56e3e2ad37df09365391a0bf4a088392_115148_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-04_hu56e3e2ad37df09365391a0bf4a088392_115148_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-04_hu56e3e2ad37df09365391a0bf4a088392_115148_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<p>在這段程式碼中，會有一個「action=」開頭，後方接著一段網址，將這段網址複製並記錄下來，後面會使用它。</p>
<p>本次所取得的網址如下（本網址為 Demo 用，非實際本站用網址）：</p>
<pre><code>https://docs.google.com/forms/u/0/d/e/1FAIpQLScBtEkMNxQJrrIK0kLJHMOUFnPqWv7Dpa7P36J7BLrGszqJuQ/formResponse
</code></pre>
<h3 id="接下來取得各欄位的-name">接下來取得各欄位的 name</h3>
<p>繼續在網頁右側的 DevTools 中搜尋「entry.」，會看到幾列 &lt;input type=&ldquo;hidden&rdquo; 開頭的程式碼，由上而下會對應到你所建立的表單欄位（依照建立順序而不是顯示順序）。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-05_hu8c12d22a7e7cb18b257212d2eb5b8fb1_69940_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-05_hu8c12d22a7e7cb18b257212d2eb5b8fb1_69940_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-05_hu8c12d22a7e7cb18b257212d2eb5b8fb1_69940_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-05_hu8c12d22a7e7cb18b257212d2eb5b8fb1_69940_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<p>在程式碼中的「name=」後方內容，就是我們所需要的 name 值，本文範例如下：</p>
<pre><code>entry.1515159479
entry.790304345
</code></pre>
<p>取得這些資訊後，就可以回到網站，準備讓資料記入 Google Sheets 囉！</p>
<h3 id="回到網站準備寫-code">回到網站準備寫 Code</h3>
<p>在這裡，我們需要取得目前網頁的網址，為了方便後續使用，這邊只需要取得網址路徑（Pathname）的部份，可以透過 「location.pathname」來取得。</p>
<pre><code class="javascript">let pageviewUrl = location.pathname;  
// 假設網址為 https://example.com/abc/  
// pageviewUrl 為 /abc/  
</code></pre>
<p>而計數的部份則固定為 1：</p>
<pre><code class="javascript">let pageviewCount = 1;</code></pre>
<p>接下來要將資料透過 $ajax POST 到 Google Forms 上（記得要先引入 jQuery）：</p>
<pre><code class="javascript">let data = {  
    'entry.1515159479': pageviewUrl,  
    'entry.790304345': pageviewCount  
};  
$.ajax({  
    type: 'POST',  
    url: 'https://docs.google.com/forms/d/e/1FAIpQLSeTgHEpVpuV_OHakO-25X-O7I4T1tIzIAUqHWLRvUqG9e6TvQ/formResponse',  
    data: data,  
    contentType: 'application/json',  
    dataType: 'jsonp'  
});</code></pre>
<p>其中，data 裡的 key 就是稍早在 Google Forms 中取得 entry. 開頭的 name，而 url 則是 Google Forms 中取得的 url。</p>
<p>完成後到瀏覽器嘗試載入網頁，應該就可以發現 Google Sheets 中出現此筆資料了。</p>
<iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vRbg3G_CI8PU6e4L-nX2dgeNPwrCy_YQSJWgB5dPoGgnrsJPgtFYz75FvJ7yL6_NakamUFJRxb8a3Ht/pubhtml?gid=1221490765&single=true&widget=true&headers=false" width="600" height="120" frameborder="0" marginheight="0" marginwidth="0" style="width: 100%;height: auto;aspect-ratio: 16 / 4;overflow: hidden;"></iframe>
<h2 id="將-google-sheets-作為資料庫使用">將 Google Sheets 作為資料庫使用</h2>
<p>接著回到 Google Sheets，我們要透過 Google Apps Script 將資料傳輸給網頁使用，但在使用前你會發現 Google Sheets 中的資料是分開一筆一筆紀錄的，但我們在實際使用上會希望是呈現不同頁面累積的流量，因此需要先在 Google Sheets 中進行基本處理。</p>
<h3 id="透過-query-函式快速整理資料">透過 QUERY 函式快速整理資料</h3>
<p>首先，先在 Google Sheets 中建立一個新分頁，我們將他命名為「Pageview」。</p>
<p>接著，這邊將會使用到 Google Sheets 的一個函式「QUERY」，這是一個可以在 Google Sheet 中方便使用 SQL 資料庫語法的函式，在進行較複雜的資料整理時相當有用，而 QUERY 的函式使用方式可參考<a href="https://support.google.com/docs/answer/3093343?hl=zh-Hant" title="對多筆資料執行 Google Visualization API Query Language 查詢作業。">官方說明</a>。</p>
<p>QUERY 函式用法：</p>
<pre><code>=QUERY(資料範圍,SQL 語法,標題[選填])
</code></pre>
<p>而在這次的資料中，我們需要的是表單回應裡的網址與計數兩欄，其中計數欄會希望是加總後的結果，因此在 Pageview 分頁中的 A1 儲存格中輸入如下公式：</p>
<pre><code>=QUERY('表單回應 1'!B:C,&quot;select B,sum(C) group by B order by sum(C) desc&quot;)
</code></pre>
<p>在 SQL 語法部份，Google Sheets 的 QUERY 函式不像一般 SQL 可以使用表頭來選取資料，而是要使用絕對位置的欄位來選取，各內容說明如下：</p>
<ul>
<li>select B, sum(C)：指將 B 欄與加總後的 C 欄選取出來。</li>
<li>group by B：因為有使用 sum 函式，必須透過 group by 來告訴系統資料的分組方式，這邊選擇 B 欄也就是網址來進行分組。</li>
<li>order by sum(C) desc：以 sum(C) 的結果遞減排序。</li>
</ul>
<p>資料進行處理後你將會得到如下的表單：</p>
<iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vRbg3G_CI8PU6e4L-nX2dgeNPwrCy_YQSJWgB5dPoGgnrsJPgtFYz75FvJ7yL6_NakamUFJRxb8a3Ht/pubhtml?gid=179157578&single=true&widget=true&headers=false" width="600" height="120" frameborder="0" marginheight="0" marginwidth="0" style="width: 100%;height: auto;aspect-ratio: 16 / 4;overflow: hidden;"></iframe>
<h3 id="用-google-apps-script-取得-google-sheets-的資料">用 Google Apps Script 取得 Google Sheets 的資料</h3>
<p>Google Apps Script 是由 Google 開發的腳本平台（Scripting Platform），支援使用 JavaScript 撰寫程式碼，除了可以串連 Google 文件、試算表等工具外，妥善使用甚至能作為輕量後端。</p>
<p>而 Google Apps Script 免費的額度是一天 2 萬次，因此對於小流量的網站基本上是相當足夠的。</p>
<h4 id="前往-google-apps-script-撰寫程式碼">前往 Google Apps Script 撰寫程式碼</h4>
<p>要前往 Google Apps Script，可以在 Google Sheets 上方選單選取「擴充功能」→ 「Apps Script」。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-06_hu73049170e172038e5f562c8eee6a9b98_26055_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-06_hu73049170e172038e5f562c8eee6a9b98_26055_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-06_hu73049170e172038e5f562c8eee6a9b98_26055_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-06_hu73049170e172038e5f562c8eee6a9b98_26055_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<p>開啟 Google Apps Script 後，就可以開始進行程式碼的撰寫了。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-07_huba052656d30312b6fa5dfb7fc336e662_64980_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-07_huba052656d30312b6fa5dfb7fc336e662_64980_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-07_huba052656d30312b6fa5dfb7fc336e662_64980_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-07_huba052656d30312b6fa5dfb7fc336e662_64980_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<h4 id="獲取-google-sheets-資料">獲取 Google Sheets 資料</h4>
<p>首先，要先讓 Google Apps Script 能讀取 Google Sheets 的資料，透過以下公式可以取得資料，並將資料轉為陣列形式。</p>
<pre><code class="javascript">var ss = SpreadsheetApp.getActiveSpreadsheet();  // 設定要取得資料的文件  
var sheet = ss.getSheetByName("Pageview");       //要取得資料的分頁名稱  
var range = sheet.getRange("A:B");               // 設定資料範圍  
var data = range.getValues();                    // 取得資料陣列</code></pre>
<p>在這裡我們可以在預設的 myFunction() 中，透過 console.log(); 的方式看一下獲取的資料內容，程式碼如下：</p>
<pre><code class="javascript">function myFunction() {  
    console.log(data);  
}</code></pre>
<p>點選畫面上方的「執行」，首次將會跳出授權畫面，點選「審查授權」。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-08_hu77f5ad15006e351d158622ff585502be_84758_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-08_hu77f5ad15006e351d158622ff585502be_84758_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-08_hu77f5ad15006e351d158622ff585502be_84758_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-08_hu77f5ad15006e351d158622ff585502be_84758_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<p>點選後會跳出警示畫面，因為這個應用程式是我們自己寫的，因此可以放心按下下方的「前往」，並選擇要授權的 Google 帳號（目前登入使用的）。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-09_hu365933289face04955e69e7348a201cb_47771_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-09_hu365933289face04955e69e7348a201cb_47771_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-09_hu365933289face04955e69e7348a201cb_47771_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-09_hu365933289face04955e69e7348a201cb_47771_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<p>取得授權後，下方執行記錄就會列出我們所選取的資料陣列內容。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-10_hu64f96f4e704dde2785b1e888939da417_42660_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-10_hu64f96f4e704dde2785b1e888939da417_42660_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-10_hu64f96f4e704dde2785b1e888939da417_42660_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-10_hu64f96f4e704dde2785b1e888939da417_42660_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<h3 id="將資料以-json-形式提供給網站">將資料以 Json 形式提供給網站</h3>
<p>Google Apps Script 取得 Google Sheets 的資料後，我們要再將資料轉成 Json 形式，讓網站能順利讀取。</p>
<p>而 Google Apps Script 的資料要能夠對外發送，必須透過一個特別的函式 doGet() 來進行：</p>
<pre><code class="javascript">function doGet() {  
    var dataExportFormat = JSON.stringify(data); // 將資料陣列轉換成為 Json 格式  
    return ContentService.createTextOutput(dataExportFormat).setMimeType(ContentService.MimeType.JSON); // 回傳資料  
}</code></pre>
<p>完成後，點選畫面上方的「部署」→「新增部署作業」。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-11_hu13a7803d69c3ae49a3d45e44a3cc44cd_100254_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-11_hu13a7803d69c3ae49a3d45e44a3cc44cd_100254_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-11_hu13a7803d69c3ae49a3d45e44a3cc44cd_100254_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-11_hu13a7803d69c3ae49a3d45e44a3cc44cd_100254_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<p>點選左方齒輪 →「網頁應用程式」。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-12_hu94f29fc572fe3d260e5580fb396607e0_43685_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-12_hu94f29fc572fe3d260e5580fb396607e0_43685_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-12_hu94f29fc572fe3d260e5580fb396607e0_43685_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-12_hu94f29fc572fe3d260e5580fb396607e0_43685_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<p>下方的「誰可以存取」改選「任何人」，並點擊「部署」。</p>
<p>
<figure>
    <picture>
        
        <source data-srcset="/src/images/post/google-app-script-article-13_hub0141eed09685ebe7217e809e80e4c97_65315_400x0_resize_q75_h2_box.webp" media="(max-width:500px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-13_hub0141eed09685ebe7217e809e80e4c97_65315_600x0_resize_q75_h2_box.webp" media="(max-width:700px)" type="image/webp">
        
        <source data-srcset="/src/images/post/google-app-script-article-13_hub0141eed09685ebe7217e809e80e4c97_65315_960x0_resize_q75_h2_box.webp" type="image/webp">
        
        <img src="/src/images/img-placeholder.svg" data-src="/src/images/post/google-app-script-article-13_hub0141eed09685ebe7217e809e80e4c97_65315_960x0_resize_q75_box.jpg" alt=""
            class="lazy"  width="960" height="540">
    </picture>
    
</figure></p>
<p>完成部署後會獲得一串網址：</p>
<pre><code class="bash">https://script.google.com/macros/s/xxxxxxxxxxxxxxxxxxx/exec</code></pre>
<p>後續將會在網站上透過此網址來串接網頁瀏覽數。</p>
<h2 id="最後一哩路用-javascript-將資料放入頁面中">最後一哩路：用 Javascript 將資料放入頁面中</h2>
<p>回到網頁，同樣使用 jQuery 的 $ajax 來串接資料，其中的 url 填入前面從 Google Apps Script 所取得的連結，程式碼如下：</p>
<pre><code>$.ajax({
    url: 'https://script.google.com/macros/s/AKfycbypNr2QBNkSkJ6FBaYz8C8o2E8IuWsB4AzL-UltX7aUeBZJ-d00uGaMm7Joy-gP2nT_Bw/exec',
    type: 'get',
    async: false,
    success: function (res) {
        // 獲取資料成功
    },
    error: function (res) {
        // 獲取資料失敗
    }
});
</code></pre>
<p>成功獲取資料後，理想中我們希望依據不同網址獲取不同瀏覽次數，因此使用一個 for 迴圈來篩選出資料：</p>
<pre><code>for (var i of res) {
    if (i[0] === pageviewUrl) { // 當 i[0] 也就是陣列中的網址 等於 本頁路徑時
        var pv = i[1]; // 讓 pv 等於 i[1] 也就是陣列中的計數
        $('#pv').text(pv); // 將 #pv 元素加入此數值
    }
}
</code></pre>
<p>最後整合 for 迴圈與 $ajax 如下：</p>
<pre><code>$.ajax({
    url: 'https://script.google.com/macros/s/AKfycbypNr2QBNkSkJ6FBaYz8C8o2E8IuWsB4AzL-UltX7aUeBZJ-d00uGaMm7Joy-gP2nT_Bw/exec',
    type: 'get',
    async: false,
    success: function (res) {
        for (var i of res) {
            if (i[0] === pageviewUrl) { // 當 i[0] 也就是陣列中的網址 等於 本頁路徑時
                var pv = i[1]; // 讓 pv 等於 i[1] 也就是陣列中的計數
                $('#pv').text(pv); // 將 #pv 元素加入此數值
            }
        }
    },
    error: function (res) {
        console.log('Error')
    }
});
</code></pre>
<p>到這裡就完成囉！</p>
<p>最後，Demo 頁面與程式碼範例都放在 GitHub 上，也歡迎大家提供其他建議囉！</p>
<ul>
<li>Demo 頁面：<a href="https://demo-uqp.pages.dev/google-app-script-article-pageview/">https://demo-uqp.pages.dev/google-app-script-article-pageview/</a></li>
<li>範例程式碼：<a href="https://github.com/chenghanxyu/google-app-script-article-pageview/">https://github.com/chenghanxyu/google-app-script-article-pageview/</a></li>
</ul>
]]></content:encoded></item></channel></rss>