Skip to content

Recaptcha not recognizing language change on first ngOnChanges call #47

@mikelseverson

Description

@mikelseverson

Background:
During initialization of the component, setupComponent calls registerCaptchaScript.

registerCaptchaScript adds the grecaptcha script tag for the language passed into the component via 'hl' binding.

If a grecaptcha script has already loaded, no script tag is added, the logic gets skipped. (see below)

    function (useGlobalDomain, render, onLoad, language) {
        var _this = this;
        if (this.grecaptchaScriptLoaded()) {
            // recaptcha script is alrseady loaded
            // just call the callback
            this.zone.run(function () {
                onLoad(window[_this.windowGrecaptcha]);
            });
            return;
        }
        // we need to patch the callback through global variable, otherwise callback is not accessible
        // note: https://github.com/Enngage/ngx-captcha/issues/2
        window[this.windowOnLoadCallbackProperty] = (/** @type {?} */ ((function () { return _this.zone.run(onLoad.bind(_this, window[_this.windowGrecaptcha])); })));
        // prepare script elem
        /** @type {?} */
        var scriptElem = document.createElement('script');
        scriptElem.innerHTML = '';
        scriptElem.src = this.getCaptchaScriptUrl(useGlobalDomain, render, language);
        scriptElem.async = true;
        scriptElem.defer = true;
        // add script to header
        document.getElementsByTagName('head')[0].appendChild(scriptElem);
    };

the issue:
first ngx-recaptcha2 component loads the grecaptcha in 'en' then is removed from dom
later a new ngx-recaptcha2 component initializes with 'fr' for a language
english gets reused on the new component, the hl value is ignored.
Now, if the second component now updates hl to 'es', ngx-recaptcha2 updates grecaptcha appropriately.

This seems to be caused by scriptService.cleanup not being called during the first hl value change.

        if (changes && changes.hl) {
            // cleanup scripts when language changes
            if (!changes.hl.firstChange && (changes.hl.currentValue !== changes.hl.previousValue)) {
                this.scriptService.cleanup();
            }
        }

Workaround:
reproducing scriptService.cleanup when destroying the first ngx-captcha seems to get the second component to initialize as expected.

  ngOnDestroy() {
    window.ngx_captcha_onload_callback = undefined;
    window.windowGrecaptcha = undefined;
  } 

Thanks for the building this out, it has been great to use!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions