Search code examples
javascriptcookiesanchorexternalgetelementbyid

How to inject (add via JavaScript) an anchor text and normal text in a cookie banner from Cookiebot (external JavaScript)?


<script>
document.getElementById("CybotCookiebotDialogBodyContentText").innerHTML += ' | <a href="https://www.google.com/">Google</a>'
</script>

I've tried this code with the console of Google Chrome. I succeeded. But if I copy and paste it in the area "JavaScript (Footer)" or "JavaScript (Header)" (Here is the external JavaScript file.) then it shows me "(index):208 Uncaught TypeError: Cannot read property 'innerHTML' of null" (possible problems: Make a declaration like !important [And where in a code of JavaScript?]? time to load the cookie banner [time difference]). Thank you.


Solution

  • The element probably doesn't exist when your Javascript is executing, which is why you're getting the error.

    The error tells you that it 'Cannot read the innerHTML of null', which means document.getElementById("CybotCookiebotDialogBodyContentText") is returning null.

    You need to wait for #CybotCookiebotDialogBodyContentText to exist, then grab it and update it.

    If the #CybotCookiebotDialogBodyContentText is available immediately when your page is loaded, just move your JS to the end of the <body> element. Otherwise you'll need to set a poll function to wait for it, like:

    function waitFor(element, f) {
        if (document.querySelector(element)) {
            f();
        } else {
            waitFor(element, f);
        }
    }
    
    waitFor('#CybotCookiebotDialogBodyContentText', function() {
        document.getElementById("CybotCookiebotDialogBodyContentText").innerHTML += ' | <a href="https://www.google.com/">Google</a>'
    })