RomanOks
RomanOks

Reputation: 712

Embedded executable JS from Rails

How to make embedded executable JS for other sites?

I have a Rails application (3000 port) in which:

routes.rb

get '/embed/:tag_name',to: 'embed_widget#tag_name'

embed_widget_controller.rb

class EmbedWidgetController < ApplicationController
  layout false, only: [:tag_name]
  protect_from_forgery except: [:tag_name]
  before_action :set_access_headers, only: [:tag_name]

  def tag_name
    @tag_name = params[:tag_name]
  end

  private

  def set_access_headers
    headers['Content-Type'] = 'text/javascript; charset=utf8'
    headers['Access-Control-Allow-Origin'] = '*'
  end
end

tag_name.html.haml

:plain
  var tag = "#{@tag_name}"
  console.log('Hello from embedded JS. Tag name =', tag)

I am inserting code to connect JS on another site (3001 port):

<div class='embed'>
  <script src='http://localhost:3000/embed/exampletagname' type='text/javascript'></script>
</div>

But nothing happens.

How to get output to console on another site?

Upvotes: 0

Views: 47

Answers (1)

Vasfed
Vasfed

Reputation: 18444

Your code serves content type text/html, but for scripts it should be text/javascript

get '/embed/:tag_name',to: 'embed_widget#tag_name', defaults: {format: :js}

and rename your view to tag_name.js.erb:

var tag = "<%= @tag_name %>";
console.log('Hello from embedded JS. Tag name =', tag)

embed as previously, or via http://localhost:3000/embed/exampletagname.js

Upvotes: 1

Related Questions