Home > Enterprise >  Iframe URL insertion from Google Sheet cell
Iframe URL insertion from Google Sheet cell

Time:07-26

I need Iframe URL to be changed several times a week, buy w/o changing the code. This is what my friend helped me with, but it still doesn't work. Please advise us. Thanks!

<iframe id="magicIframe" src="">
</iframe><script>
    const spreadsheetId = '1pekI9iqMiVkVkRAqajMjmoTfKFsfK1LNTZGcS6NYjRk';
    var iframeUrl = '';
    function sheet() {
        fetch(`https://docs.google.com/spreadsheets/d/${spreadsheetId}/gviz/tq?tqx=out:json`)
            .then(res => res.text())
            .then(text => {
                const json = JSON.parse(text.substr(47).slice(0, -2));
                iframeUrl = json.table.rows[0].c[0].v;
            });
        document.getElementById('magicIframe').src = iframeUrl;
    };
    window.onload = function(e) {
        setTimeout(() => {
            sheet();
        }, "2000")

    };
</script>

CodePudding user response:

I seemed to have got it working by moving the line where you inject the iframe URL into the DOM to be a part of your second .then callback:

const spreadsheetId = '1pekI9iqMiVkVkRAqajMjmoTfKFsfK1LNTZGcS6NYjRk';
var iframeUrl = '';

function sheet() {
    fetch(`https://docs.google.com/spreadsheets/d/${spreadsheetId}/gviz/tq?tqx=out:json`)
        .then(res => res.text())
        .then(text => {
            const json = JSON.parse(text.substr(47).slice(0, -2));
            iframeUrl = json.table.rows[0].c[0].v;
            document.getElementById('magicIframe').src = iframeUrl;
            console.log("In scope: "   iframeUrl);
        });

        console.log("Not in scope: "   iframeUrl);
};

window.onload = function(e) {
    setTimeout(() => {
        sheet();
    }, "2000")

};

If you see in the console iframeUrl is still set to the value it was instantiated with. I'm not a JavaScript under the hood expert but it is probably something to do with the way promises and callback functions work? Not sure. I hope this helps

  • Related