javascript - 从 Rails 设置 document.domain 的 DRY 方式

标签 javascript ruby-on-rails cors cross-domain

我有一个 Rails 应用程序,它使用两个想要用 JavaScript 进行通信的子域。有效设置 document.domain = mydomain.com 的最 DRY 方法是什么?

使其不那么简单的条件

  1. 在域为 localhost 的开发或测试环境中,这应该不是问题。
  2. 还需要在某些不加载主 JavaScript 文件的页面上进行设置

条件 1 让我认为我要么想要依赖从 location.host 解析根域的正则表达式,要么在 erb 中进行切换.

条件2让我觉得最好编写一次并将其放入 Assets 管道中并在必要时包含它。

最佳潜在解决方案

创建一个类似 domain_setter.js.erb 的文件(如下内容),将其添加到预编译列表中,并将其包含在所有必要的位置(\\= require domain_setter 在 list 中或 javascript_include_tag 'domain_setter' 对于没有 list 的页面)。

<%- if Rails.env.production? %>
  document.domain = 'mydomain.com';
<%- end %>

更新了当前解决方案

此解决方案更加动态,不需要对域进行硬编码。仍然不是最好的,但它正在工作......主要:-/

(function() {
  var domain = /^(?:https?\:\/\/)?.*?([^.]+\.[^.]+?)(?:\:\d+)?$/.exec(location.host);

  if (domain == null) {
    document.domain = 'localhost';
  } else {
    document.domain = domain[1];
  }
})();

tl;博士

使用 Rails 设置多个页面的 document.domain 的 DRY 方法是什么?

最佳答案

我认为您正在寻找跨源资源共享(CORS)。这允许 javascript 跨不同域发出 AJAX $.get/post 请求。

这是一个可以帮助您入门的 Rails 库:https://github.com/cyu/rack-cors#rails

您需要将 origins 属性设置为 yoursubdomain.herokuapp.com

关于javascript - 从 Rails 设置 document.domain 的 DRY 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35705950/

相关文章:

ruby-on-rails - ActiveRecord 查询以获取跨表的 SUM

ruby-on-rails - 如何测试也定义为辅助方法的 ApplicationController 方法?

javascript - 在组件中通过类名 react 访问dom元素

javascript - 如何使用 Lodash.js 删除数组项?

javascript - 在 xpages 中使用 dojox 网格

ruby-on-rails - Rails 测试和 Mocha : How to stub specific model - conditional any_instance?

javascript - 捕获 'Blocked loading mixed active content' CORS 错误

javascript - 如何在静态 Github 页面上发出 WolframAlpha 请求?

javascript - CORS – 跨域请求被阻止 – 'Access-Control-Allow-Origin' header 包含无效值

javascript - ng-repeat 的 img 标签中的 data-original 属性中的转义链接