到了這一章,IP 查詢、位置顯示都已經能正常運作了。接下來,我希望這個網站不只是好玩,而是可以 稍微幫自己「回點本」,所以我開始思考要在頁面中加入 Google 廣告,讓這個小專案多一點實際價值。
對於這種簡單的工具型網站來說,我不需要複雜的廣告系統,只要有人使用、有人瀏覽,就有機會產生一點收益。 Google AdSense 適合這種做法,只要通過審核,就能拿到一段廣告程式碼,把它放到網站中就能開始顯示廣告。
在申請並通過 AdSense 審核後,可以在後台建立一個廣告單元,Google 會給你一段像這樣的程式碼:
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
data-ad-slot="yyyyyyyyyy"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle=window.adsbygoogle||[]).push({})
</script>
裡面的 data-ad-client 和 data-ad-slot 是你的專屬帳號與廣告代號,
這兩個要照後台給的填。
因為我不想在頁面中到處貼同樣的廣告程式碼,所以我把它包成一個單獨的元件,之後只要在頁面上 放一個標籤,就能顯示廣告,維護也比較輕鬆。
import {useEffect} from "react"
function AdComponent(){
useEffect(function(){
if(window.adsbygoogle){
window.adsbygoogle.push({})
}
},[])
return(
<ins className="adsbygoogle"
style={{display:"block"}}
data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
data-ad-slot="yyyyyyyyyy"
data-ad-format="auto"
data-full-width-responsive="true">
</ins>
)
}
export default AdComponent
之後在頁面中要放廣告,就只需要寫:
<AdComponent />
這樣一來,就能在 IP 查詢結果下方顯示一個廣告區塊,版面也會比亂塞 script 還要乾淨。
在這一章,我讓這個 IP 查詢網站多了一個「可以變現」的功能。不過我也很清楚,廣告只是配角, 不能影響整體使用體驗,因此我把廣告集中在特定區塊,避免擋住主要內容。
下一章,我會把這個專案真正部署到伺服器上,讓這個 IP 查詢網站不再只存在於本機,而是任何人 都可以透過網址直接使用。





