从另一个应用程序访问javascript文件

To access javascript files from another app

本文关键字:javascript 文件 访问 应用程序 另一个      更新时间:2023-09-26

我正试图从另一个访问我的应用程序的预编译文件。我有一个特定的架构。这是一个简化的树

├── app
│   ├── assets
│   │   ├── javascripts
│   │   │   ├── application.coffee
│   │   │   ├── my_js_file.coffee
├── my-other-app
│   ├── index.html
│   ├── javascript
│   │   ├── anotherJSFile.js

我想在index.html上加载my_js_file.coffee的编译文件。

my-other-app不是一个Rails应用程序。它包含一个基本的index.html文件,其中一个特定的URL重定向,我尝试类似的东西:

<script src="http://myapp.com/assets/my_js_file.js"></script>

我已经在Apache配置文件上定义了它(这部分是可以的)。

我的问题是,我找不到任何方法来访问编译的my_js_file.js文件。对文件的访问和文件名本身(带指纹)。我怎么解决这个问题呢?

编辑:

我认为主要问题来自指纹,因为我需要知道它来动态地适应我的url在我的第二个应用程序。

Edit2: 我找到了一种方法来生成动态url与正确的指纹,但我仍然无法访问编译文件(未经授权)

我做到了,但是有点棘手。

有两个点:

  1. js指纹
  2. 从rails应用程序到其他网页(在此rails应用程序环境之外)的认证令牌

为了解决第一个问题,我必须在模型上创建一个方法,我在部署结束时调用它(使用capistrano)来动态修改我的index.html文件。我是这样做的:

#my-other-app/index.html
<!doctype html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <!-- BEGIN DYNAMIC URI -->
        <!-- END DYNAMIC URI -->
    </head>
    <body >
        <div id="awesome">
            Some stuff here..
        </div>
    </body>
</html>

#myModel.rb
def self.generate_index_file
  js_files = ['my_js_file.js']
  tempfile = File.open Rails.root.join('my-other-app/index.tmp'), 'w'
  f = File.new('my-other-app/index.html')
  f.each do |line|
    if line =~ /^.*<!-- BEGIN DYNAMIC URI -->/
      tempfile << line
      js_files.each do |filename|
        fingerprinted_name = Rails.application.assets.find_asset(filename).digest_path
        tempfile << "<script src='#{Rails.application.default_url_options[:host]}/assets/" + fingerprinted_name + "?body=1'></script>'n"
      end
    else
      tempfile << line
    end
  end
  f.close       
  tempfile.close
  FileUtils.mv("my-other-app/index.tmp", "my-other-app/index.html")
end

#config/deploy/production.rb
# Available only for Capistrano 2.x
namespace :deploy do
  task :generate_samsung_index, roles: :app do
    run %Q{cd #{latest_release} && RAILS_ENV=#{rails_env} bundle exec rails runner 'MyModel.generate_index_file'}
  end 
end
after "deploy:restart", "deploy:generate_samsung_index"

现在,为了解决问题的第二部分(身份验证部分),我需要在将url添加到<head>之前向url添加令牌。下面是我的代码:

#my_models_controller.rb
def my_method
  redirect_to "http://myawesomeurl.com?token=#{form_authenticity_token}"
end

#my-other-app/index.html
# On <head> with my previous code
<script language="javaScript" type="text/javascript">
   meta1 = document.createElement("meta");
   meta1.name = "csrf-param";
   meta1.content = "authenticity_token";
   $("head").append(meta1);
   token = "token"
   token_result = new RegExp(token + '=([^&]*)', 'i').exec(window.location.search)
   meta2 = document.createElement("meta");
   meta2.name = "csrf-param";
   meta2.content = token_result;
   $("head").append(meta1);
   $("head").append(meta2);
 </script>