1
votes

I want to insert my block of HTML into a Shopify shop after a certain section but the problem is that each shop can use one of thousands of different themes, each one having a different DOM structure.

I can create the Script Tag and I can try to insert my HTML like this:

(function() {
  var child = document.createElement("div");
  var text  = document.createTextNode("This is a test message");
  child.appendChild(text);

  var parent = document.getElementByClassName("ProductSection");
  parent.appendChild(child);
})();

And this will work if the theme has a section with a class name of ProductSection but it won't for the majority of them that don't. Let's say I have an image gallery I'd like to show but only on Product pages and after the product description, what's the best way to select the product description DOM node so that I can insert my image gallery after it?

I found a couple threads with similar problems:

https://community.shopify.com/c/Shopify-APIs-SDKs/Using-Script-tag-to-add-dynamic-content-to-product-template/m-p/457855 https://community.shopify.com/c/Shopify-APIs-SDKs/Need-to-add-a-button-to-the-Product-page-via-a-Script-Tag/m-p/413919

and they seem to come to a similar conclusion, yet there are apps on the Shopify app market that do exactly this, and I wonder how do they do it?

1

1 Answers

3
votes

As suggested in the links shared by you, it is not possible to correctly identify the DOM element in all the cases. However, there are couple of different approaches that can be used.

1) One is to ask merchant to add some specific element to markup that you can later use for rendering your content via JavaScript.

2) Try to guess the DOM element via some specific tag or href value, but allow merchants to override the DOM element selector via some JavaScript variable.

3) Use approach 2 with a combination of pre-determined info. Saw this approach used by AfterPay. They have a pre-defined array of popular themes along with their selectors. Then they use the theme name property from Shopify.theme.name and get the relevant selectors. This solution may not work in all cases, so do allow the merchant to override DOM selector via some JavaScript variable.

Afterpay.supportedThemes = {
    alchemy: {
        product: {
            "2017-12-14": {
                selector: ".quadd-wrapper"
            }
        }
    }
}

AfterPay JS Source Code

If you know of any other plugins, you can inspect the JavaScript and have a look how they identify the selectors.