I recently started Shopify application development because I want to make an application that the user installs and puts an external JavaScript file into their theme (preferably that only load in products.liquid).
I experimented with some Rails code with ScriptTag and I get the JavaScript file to be inserted into the HTML, but it never loads.
I made the following change in app/controllers/sessions_controller.rb after this code:
def show
if response = request.env['omniauth.auth']
sess = ShopifyAPI::Session.new(params[:shop], response['credentials']['token'])
session[:shopify] = sess
(AFTER) MY CODE:
ShopifyAPI::Base.activate_session(sess)
ShopifyAPI::ScriptTag.create(:event => "onload", :src => "//x.com/x/myscript.js")
As I said, when I inspected the element in Chrome, I see that myscript.js is inserted, but it never loads.
Is it something to do with 'async' being 'true'? Is there a way to use ScriptTag and tell that it is not an async load?
Or, is there another way around this? I searched both the API and forum for some answers but they got me very confused. Maybe I need some directions in the right path?
What should I do to develop a Shopify application in Ruby on Rails that simply inserts a JavaScript file into the owners shop? And can I make it load only in some pages, like products?
Yes, you can do it right. See document on Shopify.com: Shopify API reference > Asset
PUT takes care of both creating new assets and updating existing ones
Do a POST request to Shopify's ScriptTag API.
POST /admin/api/2020-04/script_tags.json
{
"script_tag": {
"event": "onload",
"src": "https://your.dev/script.js"
}
}
Curl example:
curl -X POST "https://$SHOP.myshopify.com/admin/api/2020-04/script_tags.json" -H "X-Shopify-Access-Token: $ACCESS_TOKEN" -d "$PAYLOAD"
From that point onwards your script will always be included on the storefront, until the merchant uninstalls your app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With