Skip to content

Commit

Permalink
feat: add support for GTM event logging if available
Browse files Browse the repository at this point in the history
  • Loading branch information
namanaman committed Jun 28, 2024
1 parent 0ee3b8c commit 2971244
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
5 changes: 5 additions & 0 deletions feedback-widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ function logGoogleEvent(action, label = undefined) {
event_category: "Page feedback",
event_label: label,
});
} else if (window.dataLayer != null) {
window.dataLayer.push({
event: "click_feedback_rating",
object_type: label,
});
}
}

Expand Down
2 changes: 1 addition & 1 deletion feedback-widget.min.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function logGoogleEvent(action,label=void 0){"function"==typeof window.gtag&&window.gtag("event",action,{event_category:"Page feedback",event_label:label})}let LANG_TO_CONTENT={en:{ratingPrompt:"Did you find what you were looking for on this page?",ratingPositive:"Yes",ratingNegative:"No",commentPromptPositive:"Great! We're looking for ways to improve this page — what ideas come to mind?",commentPromptNegative:"Sorry to hear that. What were you looking for today?",commentPromptDisclaimer:"Your feedback helps improve this web page. For specific questions about your situation, ",commentPromptDisclaimerLink:"contact us",commentSubmit:"Send feedback",commentSubmitLoading:"Sending...",commentConfirmation:"Thanks for sharing your thoughts!",emailPrompt:"To hear about paid feedback opportunities in the future, join our user testing list.",emailLabel:"Email address",emailSubmit:"Join the list",emailSubmitLoading:"Joining...",errorMessage:"Try again, please. We didn't get your answer because of a technical issue.",emailConfirmation:"Thanks for signing up!"},es:{ratingPrompt:"¿Encontraste lo que buscabas en esta página?",ratingPositive:"Sí",ratingNegative:"No",commentPromptPositive:"¡Excelente! Estamos buscando formas de mejorar esta página. ¿Qué ideas se te ocurren?",commentPromptNegative:"Lamentamos escuchar eso. ¿De que se trataba su búsqueda?",commentPromptDisclaimer:"Sus comentarios nos ayudan a mejorar nuestro sitio de web. Si tiene preguntas específicas sobre su situación, ",commentPromptDisclaimerLink:"por favor póngase en contacto con nosotros",commentSubmit:"Enviar comentarios",commentSubmitLoading:"Enviando...",commentConfirmation:"¡Gracias por compartir tus ideas!",emailPrompt:"Para conocer mas oportunidades de comentarios pagados en el futuro, sea parte de nuestra lista de prueba de usuarios.",emailLabel:"Dirección de correo electrónico",emailSubmit:"Sea parte de la lista",emailSubmitLoading:"Enviando...",errorMessage:"Por favor, inténtalo de nuevo. No obtuvimos su respuesta debido a un problema técnico.",emailConfirmation:"¡Gracias por registrarte!"}},API_URL="https://innovation.nj.gov/app/feedback/dev",JSON_HEADER={"Content-Type":"application/json"};class NJFeedbackWidget extends window.HTMLElement{constructor(){super(),this.rating=!1,this.feedbackId=void 0,this.retryRating=!1,this.language=new URL(window.location).searchParams.get("lang")??"en"}connectedCallback(){this.innerHTML=this.getHTML(),this.applyListeners(),this.addStyling(),document.addEventListener("changeLanguage",this.handleChangeLanguage.bind(this))}disconnectedCallback(){document.removeEventListener("changeLanguage",this.handleChangeLanguage.bind(this))}handleChangeLanguage(e){this.language=e.detail,this.innerHTML=this.getHTML(),this.applyListeners()}applyListeners(){this.querySelector("#yesButton").addEventListener("click",_e=>{this.handleRating(!0)}),this.querySelector("#noButton").addEventListener("click",_e=>{this.handleRating(!1)}),this.querySelector("#commentForm").addEventListener("submit",e=>{e.preventDefault();let submitButton=document.getElementById("commentSubmit");submitButton.disabled=!0,submitButton.textContent=LANG_TO_CONTENT[this.language].commentSubmitLoading,this.hideElement("#commentSubmitError");e=e.target.elements.comment.value,e=this.retryRating||null==this.feedbackId?{comment:e,rating:this.rating,pageURL:window.location.href}:{feedbackId:this.feedbackId,comment:e};fetch(API_URL+"/comment",{method:"POST",headers:JSON_HEADER,body:JSON.stringify(e)}).then(response=>response.json()).then(data=>{null==this.feedbackId&&(this.feedbackId=data.feedbackId),"Success"===data.message&&null!=this.feedbackId?(this.hideElement("#commentPrompt"),"true"===this.getAttribute("skip-email-step")?this.showElement("#confirmation","flex"):this.showElement("#emailPrompt")):this.showElement("#commentSubmitError")}).catch(e=>{this.showElement("#commentSubmitError")}).finally(()=>{submitButton.disabled=!1,submitButton.textContent=LANG_TO_CONTENT[this.language].commentSubmit})}),this.querySelector("#emailForm").addEventListener("submit",e=>{e.preventDefault();let submitButton=document.getElementById("emailSubmit");submitButton.disabled=!0,submitButton.textContent=LANG_TO_CONTENT[this.language].emailSubmitLoading,this.hideElement("#emailSubmitError");e={feedbackId:this.feedbackId,email:e.target.elements.email.value};fetch(API_URL+"/email",{method:"POST",headers:JSON_HEADER,body:JSON.stringify(e)}).then(response=>response.json()).then(data=>{"Success"===data.message&&null!=data.feedbackId?(this.hideElement("#emailPrompt"),this.showElement("#confirmation","flex")):this.showElement("#emailSubmitError")}).catch(e=>{this.showElement("#emailSubmitError")}).finally(()=>{submitButton.disabled=!1,submitButton.textContent=LANG_TO_CONTENT[this.language].emailSubmit})})}handleRating(rating){var postData;(this.rating=rating)||(this.querySelector("#commentPromptText").innerText=LANG_TO_CONTENT[this.language].commentPromptNegative),this.hideElement("#ratingPrompt"),this.showElement("#commentPrompt"),"true"===this.getAttribute("only-save-rating-to-analytics")?logGoogleEvent("Clicked initial button",rating?"Yes":"No"):(document.getElementById("commentSubmit").disabled=!0,postData={pageURL:window.location.href,rating:rating},fetch(API_URL+"/rating",{method:"POST",headers:JSON_HEADER,body:JSON.stringify(postData)}).then(response=>response.json()).then(data=>{"Success"===data.message&&null!=data.feedbackId?(this.feedbackId=data.feedbackId,logGoogleEvent("Clicked initial button",rating?"Yes":"No")):this.retryRating=!0}).catch(e=>{this.retryRating=!0}).finally(()=>{document.getElementById("commentSubmit").disabled=!1}))}showElement(selector,displayType="block"){this.querySelector(selector).style.display=displayType}hideElement(selector){this.querySelector(selector).style.display="none"}getHTML(){var content=LANG_TO_CONTENT[this.language],contactLink=this.getAttribute("contact-link")||"https://www.nj.gov/nj/feedback.html",showCommentDisclaimer="false"!==this.getAttribute("show-comment-disclaimer");return`
function logGoogleEvent(action,label=void 0){"function"==typeof window.gtag?window.gtag("event",action,{event_category:"Page feedback",event_label:label}):null!=window.dataLayer&&window.dataLayer.push({event:"click_feedback_rating",object_type:label})}let LANG_TO_CONTENT={en:{ratingPrompt:"Did you find what you were looking for on this page?",ratingPositive:"Yes",ratingNegative:"No",commentPromptPositive:"Great! We're looking for ways to improve this page — what ideas come to mind?",commentPromptNegative:"Sorry to hear that. What were you looking for today?",commentPromptDisclaimer:"Your feedback helps improve this web page. For specific questions about your situation, ",commentPromptDisclaimerLink:"contact us",commentSubmit:"Send feedback",commentSubmitLoading:"Sending...",commentConfirmation:"Thanks for sharing your thoughts!",emailPrompt:"To hear about paid feedback opportunities in the future, join our user testing list.",emailLabel:"Email address",emailSubmit:"Join the list",emailSubmitLoading:"Joining...",errorMessage:"Try again, please. We didn't get your answer because of a technical issue.",emailConfirmation:"Thanks for signing up!"},es:{ratingPrompt:"¿Encontraste lo que buscabas en esta página?",ratingPositive:"Sí",ratingNegative:"No",commentPromptPositive:"¡Excelente! Estamos buscando formas de mejorar esta página. ¿Qué ideas se te ocurren?",commentPromptNegative:"Lamentamos escuchar eso. ¿De que se trataba su búsqueda?",commentPromptDisclaimer:"Sus comentarios nos ayudan a mejorar nuestro sitio de web. Si tiene preguntas específicas sobre su situación, ",commentPromptDisclaimerLink:"por favor póngase en contacto con nosotros",commentSubmit:"Enviar comentarios",commentSubmitLoading:"Enviando...",commentConfirmation:"¡Gracias por compartir tus ideas!",emailPrompt:"Para conocer mas oportunidades de comentarios pagados en el futuro, sea parte de nuestra lista de prueba de usuarios.",emailLabel:"Dirección de correo electrónico",emailSubmit:"Sea parte de la lista",emailSubmitLoading:"Enviando...",errorMessage:"Por favor, inténtalo de nuevo. No obtuvimos su respuesta debido a un problema técnico.",emailConfirmation:"¡Gracias por registrarte!"}},API_URL="https://innovation.nj.gov/app/feedback/dev",JSON_HEADER={"Content-Type":"application/json"};class NJFeedbackWidget extends window.HTMLElement{constructor(){super(),this.rating=!1,this.feedbackId=void 0,this.retryRating=!1,this.language=new URL(window.location).searchParams.get("lang")??"en"}connectedCallback(){this.innerHTML=this.getHTML(),this.applyListeners(),this.addStyling(),document.addEventListener("changeLanguage",this.handleChangeLanguage.bind(this))}disconnectedCallback(){document.removeEventListener("changeLanguage",this.handleChangeLanguage.bind(this))}handleChangeLanguage(e){this.language=e.detail,this.innerHTML=this.getHTML(),this.applyListeners()}applyListeners(){this.querySelector("#yesButton").addEventListener("click",_e=>{this.handleRating(!0)}),this.querySelector("#noButton").addEventListener("click",_e=>{this.handleRating(!1)}),this.querySelector("#commentForm").addEventListener("submit",e=>{e.preventDefault();let submitButton=document.getElementById("commentSubmit");submitButton.disabled=!0,submitButton.textContent=LANG_TO_CONTENT[this.language].commentSubmitLoading,this.hideElement("#commentSubmitError");e=e.target.elements.comment.value,e=this.retryRating||null==this.feedbackId?{comment:e,rating:this.rating,pageURL:window.location.href}:{feedbackId:this.feedbackId,comment:e};fetch(API_URL+"/comment",{method:"POST",headers:JSON_HEADER,body:JSON.stringify(e)}).then(response=>response.json()).then(data=>{null==this.feedbackId&&(this.feedbackId=data.feedbackId),"Success"===data.message&&null!=this.feedbackId?(this.hideElement("#commentPrompt"),"true"===this.getAttribute("skip-email-step")?this.showElement("#confirmation","flex"):this.showElement("#emailPrompt")):this.showElement("#commentSubmitError")}).catch(e=>{this.showElement("#commentSubmitError")}).finally(()=>{submitButton.disabled=!1,submitButton.textContent=LANG_TO_CONTENT[this.language].commentSubmit})}),this.querySelector("#emailForm").addEventListener("submit",e=>{e.preventDefault();let submitButton=document.getElementById("emailSubmit");submitButton.disabled=!0,submitButton.textContent=LANG_TO_CONTENT[this.language].emailSubmitLoading,this.hideElement("#emailSubmitError");e={feedbackId:this.feedbackId,email:e.target.elements.email.value};fetch(API_URL+"/email",{method:"POST",headers:JSON_HEADER,body:JSON.stringify(e)}).then(response=>response.json()).then(data=>{"Success"===data.message&&null!=data.feedbackId?(this.hideElement("#emailPrompt"),this.showElement("#confirmation","flex")):this.showElement("#emailSubmitError")}).catch(e=>{this.showElement("#emailSubmitError")}).finally(()=>{submitButton.disabled=!1,submitButton.textContent=LANG_TO_CONTENT[this.language].emailSubmit})})}handleRating(rating){var postData;(this.rating=rating)||(this.querySelector("#commentPromptText").innerText=LANG_TO_CONTENT[this.language].commentPromptNegative),this.hideElement("#ratingPrompt"),this.showElement("#commentPrompt"),"true"===this.getAttribute("only-save-rating-to-analytics")?logGoogleEvent("Clicked initial button",rating?"Yes":"No"):(document.getElementById("commentSubmit").disabled=!0,postData={pageURL:window.location.href,rating:rating},fetch(API_URL+"/rating",{method:"POST",headers:JSON_HEADER,body:JSON.stringify(postData)}).then(response=>response.json()).then(data=>{"Success"===data.message&&null!=data.feedbackId?(this.feedbackId=data.feedbackId,logGoogleEvent("Clicked initial button",rating?"Yes":"No")):this.retryRating=!0}).catch(e=>{this.retryRating=!0}).finally(()=>{document.getElementById("commentSubmit").disabled=!1}))}showElement(selector,displayType="block"){this.querySelector(selector).style.display=displayType}hideElement(selector){this.querySelector(selector).style.display="none"}getHTML(){var content=LANG_TO_CONTENT[this.language],contactLink=this.getAttribute("contact-link")||"https://www.nj.gov/nj/feedback.html",showCommentDisclaimer="false"!==this.getAttribute("show-comment-disclaimer");return`
<div class="feedback-container">
<div id="ratingPrompt" class="flex-box">
<span class="feedback-text">${content.ratingPrompt}</span>
Expand Down

0 comments on commit 2971244

Please sign in to comment.