Bernard Polman
Bernard Polman

Reputation: 855

Cannot read property of replace 'undefined' on iframe element

UPDATE: Found out that reCaptcha script was loaded in another partial view which caused the iFrame to not exist because the google API script wouldn't load before everything else!

I'm implementing localization of reCaptcha v2. However, I'm recieving a jQuery 3.3.1 error "Cannot read property 'replace' of undefined".

function setRecaptchaLanguage() {
    var lang = 'hr';
    switch (window.localStorage.getItem('activeCulture')) {
        case 'hr':
            lang = 'hr';
            break;
        case 'en-US-POSIX':
            lang = 'en';
            break;
    }

    if (window.localStorage.getItem('language') == 'ru-RU') {
        lang = 'ru';
        window.localStorage.setItem('language', null);
    }

    // Get GoogleCaptcha iframe
    debugger
    var iframeGoogleCaptcha = $('#captchaElement').find('iframe');
    // For setting new language
    if (iframeGoogleCaptcha != null)
        iframeGoogleCaptcha.attr("src", iframeGoogleCaptcha.attr("src").replace(/hl=(.*?)&/, 'hl=' + lang + '&'));

}

 $(document).ready(function () {
    //set reCaptcha language
    setRecaptchaLanguage();
});

This error doesn't come up every time and I'm still having a hard time pinpointing this problem. It occurs when switching languages but the 'iFrameGoogleRecaptcha' is not null even when I receive this error. I've googled the problem but most answers point to non-existing element that I'm trying to use 'replace' on but I don't understand how that could be an issue if the element is never null.

Any suggestions?

Upvotes: 0

Views: 586

Answers (1)

tagurit
tagurit

Reputation: 558

You shouldn't just be checking if iframeGoogleCaptcha is null, you should be worried about its src since that's the thing you're accessing. Change if (iframeGoogleCaptcha != null) to if (iframeGoogleCaptcha.attr("src") != undefined). This will make the error go away and make nothing happen instead, but hopefully you'll be able to see what's happening more clearly.

Upvotes: 2

Related Questions