Ad

Shopify - Add Automatically Javascript To Template

- 1 answer

Is it possible to add automatically some js library to template <head> section during app installation?

Given I:

  1. Downloaded this repo: https://github.com/Shopify/shopify_app
  2. Edited config/initializers/shopify_app.rb and added this line config.scope = "read_orders, read_products, read_themes, write_themes"
  3. Put this line to the controller: ShopifyAPI::Asset.create(key: 'assets/angular.js', src: 'https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js') where angular.js is my library.

I am able to use angular in the template but, I must add in the <head> section this code {{ 'angular.js' | asset_url | script_tag }}. Can I add this code automatically during app installation?

Ad

Answer

Under config/initializers/shopify_app.rb you must add to csope parameter what permission you need. config.scope = "read_orders, read_products, read_themes, write_themes, write_script_tags, read_script_tags"
In this case we need write_script_tags. After that you must add some script from cotroller, for example:

st = ShopifyAPI::ScriptTag.new(:src => "https://rawgit.com/someurl/10a5bf06d1b77a871426/raw/40a5c536453783d8b2b5ec3705ec13688bd3407c/widget.js", :event => "onload")
st.save

Your js file might look like this one:

  (function () {
    'use strict';

    var matches = document.getElementsByTagName("someTag")[0];
    console.log(matches);

  }());
Ad
source: stackoverflow.com
Ad