Prevent Tab or Window Switching | XM Community
Skip to main content

Does anyone have custom javascript code that will create a pop-up warning when participants try to switch tabs or windows?

 

THANKS!

Hi @ks13 
This is a code I did earlier for my client test, hope t can help you. The code will pop-up an alert when user switch tab and comeback. I flag the result with embedded data as warning in the 1st time and compromised in 2nd time. You can change the message as you like.

Qualtrics.SurveyEngine.addOnload(function() {

var tabSwitched = false;

window.addEventListener('blur', function() {
if (!tabSwitched) {
alert("!!! Please do not switch tabs during the test. Switching tabs again will flag your result as compromised !!!");
tabSwitched = true;
Qualtrics.SurveyEngine.setEmbeddedData('compromised', 'Warning');
} else {
alert("!!! Your result is compromised !!!");
Qualtrics.SurveyEngine.setEmbeddedData('compromised', 'Yes');
}
});

});

Hope it help


Thanks so much! I will try to implement and let you know if it works.


It did work! Thanks.


@Nam Nguyen Two follow up questions.

  1. Is there a way to alter the code you wrote so the embedded variable counts the number of blur events?
  2. I want to implement this on the whole survey except for a single page. I use captcha in the survey, and the error message is being triggered by it. I added the code to the header. Do you know how to add an exception so the errors don’t display for a given block or page?

Thanks again for your help!


@ks13 

  1. Just change the flag tabSwitched to a variable that count, save that number in embeddedData and get it again when the page load.
  2. Captcha is from google and consider an outside window. The solution is to stop the eventListener when page unload, and add the code to a question on each page, except the captcha one.

Here’s the modified version that do both
 

Qualtrics.SurveyEngine.addOnload(function () {

let tabSwitchCount = parseInt(Qualtrics.SurveyEngine.getEmbeddedData('tabSwitchCount')) || 0;

const blurHandler = function () {
tabSwitchCount++;
Qualtrics.SurveyEngine.setEmbeddedData('tabSwitchCount', tabSwitchCount);

if (tabSwitchCount === 1) {
alert("!!! Please do not switch tabs during the test. Switching tabs again will flag your result as compromised !!!");
Qualtrics.SurveyEngine.setEmbeddedData('compromised', 'Warning');
} else {
alert("!!! Your result is compromised !!!");
Qualtrics.SurveyEngine.setEmbeddedData('compromised', 'Yes');
}
};


window.addEventListener('blur', blurHandler);


Qualtrics.SurveyEngine.addOnUnload(function () {
window.removeEventListener('blur', blurHandler);
});
});

 


This worked perfectly. Thanks again for all your help!!


Leave a Reply