0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

I did everything as you wrote. But still nothing is happening :с In tag_name.js.erb, I left only console.log('Hello from embedded JS')
@RomanOks check if it renders correctly by directly requesting curl -v http://localhost:3000/embed/exampletagname.js, also check if the other site disables the script via CSP
HTTP/1.1 200 OK, Content-Type: text/javascript; charset=utf8, X-Content-Type-Options: nosniff, Access-Control-Allow-Origin: *, < console.log('Hello from embed JS')
I just tried to start another server (site) and it worked! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.