gonca
gonca

Reputation: 91

google trusted stores on single app application

Has anyone tried to implement google trusted store badges on single app pages?

My badge appears on the first time that I access the page but when I go another page, like product detail page, the badge disappears.

I couldn't find any reference on google about it.

Upvotes: 3

Views: 151

Answers (1)

Jack
Jack

Reputation: 9548

Same problem here. I read through the script that is inserted by Google Trusted Stores, and they don't provide any public method to re-initialize the script, or a destroy method to revert the changes they've already made to your document.

As a dirty last resort, you can manually remove the badge and previous script, then include the script again to have it re-run. There is a small caveat here... the first time the script runs it creates a read-only property on the window object, window.GoogleTrustedStore. The script won't run a second time if that property is defined.

You can prevent this property from being configured as readonly if you define it before Google's script does. Here's an example of all of this:

// Define object as configurable before Google Trusted Stores locks it.
// Need to be able to overwrite this property later to re-initiliaze the script.
Object.defineProperty(window, 'GoogleTrustedStore', {configurable: true});

var gts = window.gts || [];
gts.push(["locale", "en_US"]);
// ... finish defining your gts options

// Insert the GTS script to run it:
(function() {
    const script = document.createElement("script");
    script.src = "//www.googlecommerce.com/trustedstores/api/js";
    const s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(script, s);
})();

// Using timeout for demonstration purposes
setTimeout(function(){
    // Dirty example of destroying the existing badge
    var dirtyDestroy = document.querySelectorAll('#gts-comm, #gts-c, script[src^="http://www.googlecommerce.com"], script[src^="https://www.googlecommerce.com"], script[src^="http://www.gstatic.com/trustedstores"], script[src^="https://www.gstatic.com/trustedstores"]');
    [].slice.call(dirtyDestroy,0).forEach(function(el){el.parentNode.removeChild(el)});

    // Reset window.GoogleTrustedStore
    Object.defineProperty(window, 'GoogleTrustedStore', {value: undefined});

    // Insert the script again to re-run it:
    (function() {
        const script = document.createElement("script");
        script.src = "//www.googlecommerce.com/trustedstores/api/js";
        const s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(script, s);
    })();
}, 5000);

Upvotes: 1

Related Questions