# Title閃爍效果-React、JS ###### tags: `React` `JS` 看了某個網站的提示「有新訊息」是使用html head裡的title tag閃爍表現,目的應該是為了讓user在其他逛其他網站時也能注意到有新訊息進來,雖然用這種方式有可能會太干擾user,或是頁籤太多也會看不到效果,但看到了就想說來玩玩看,以下事實做成我  說是說react,實際上是直接操作document.title去做事 ````jsx const INIT_TITLE = "Howard's React App" const NEW_MSG_TITLE = 'you got new message' const UNICODE_LEFT_TO_RIGHT = '\u200E' const UTF16_LEFT_TO_RIGHT = String.fromCharCode(8206) //alternative option const HTML_ENTITY_LEFT_TO_RIGHT = `‎` // this won't work const PagetitleTransformer = () => { const [notify, setNotify] = useState(false) useEffect(() => { let id = null if (notify) { id = setInterval(() => { if (document.title === INIT_TITLE || document.title === UNICODE_LEFT_TO_RIGHT) document.title = NEW_MSG_TITLE else document.title = UNICODE_LEFT_TO_RIGHT }, [1000]) } else document.title = INIT_TITLE return () => { clearInterval(id) } }, [notify]) return ( <div> <Button variant='contained' color='secondary' onClick={(e, value) => setNotify(!notify)}> click to see tab title transform </Button> </div> ) } ```` 幾個重點: 1. title如果為空,或者是空白、tab,雖然從html中看確實沒有值,但瀏覽器會自動顯示當前網頁的網址 2. 所以為了要能正確顯示「有值→看起來空白→有值」,查看該網站顯示的方式,是使用HTML entity`‎`(超久沒用HTML entity連這個專有名詞都忘了😭) 3. 參考[本篇文章](https://dirask.com/posts/JavaScript-no-break-non-breaking-space-in-string-jMwzxD),嘗試使用`document.title = '‎'`,或給title tag一個id並且用textContent等方法寫入`‎`,無法正確顯示,title真的會變成字串`‎`,但其實該文章已有正解,只是我眼殘沒注意到...詳見下條 4. 嘗試用unicode的寫法無法達成效果,但其實人家已經寫在旁邊了,才是在js中uncode正確的表示方式 5. 最後是找到了古老的[React官方文件](https://shripadk.github.io/react/docs/jsx-gotchas.html),有特別寫到如何在JSX裡使用HTML entity,推薦的方式是使用`String.fromCharCode(8206)`或使用unicode的寫法`'\u200E'`,直到這邊我才發現我輸入unicode的語法錯誤所以才會沒東西,只能說我對字元真的不熟QQ
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up