问题
I have a Rails app that is using two subdomains which would like to communicate in JavaScript. What would be the most DRY way to effectively set document.domain = mydomain.com
?
Conditions that make it less than straight forward
- This should not be a problem in the development or test environments where the domain is
localhost
. - This needs to also be set on certain pages which don't load the main JavaScript file
Condition 1
leads me to think I either want to rely on a Regex that parses the root domain out of location.host
or do the switching in erb
.
Condition 2
makes me feel it would be best to write this once and put it in the asset pipeline and include it where necessary.
Best Potential Solution
Create a file like domain_setter.js.erb
(contents below), add it to precompile list, and include it in all necessary places (either \\= require domain_setter
in manifests or javascript_include_tag 'domain_setter'
for pages without manifests).
<%- if Rails.env.production? %>
document.domain = 'mydomain.com';
<%- end %>
Updated Current Solution
This solution is more dynamic and doesn't require hardcoding a domain. Still not the best but it's working ... mostly :-/
(function() {
var domain = /^(?:https?\:\/\/)?.*?([^.]+\.[^.]+?)(?:\:\d+)?$/.exec(location.host);
if (domain == null) {
document.domain = 'localhost';
} else {
document.domain = domain[1];
}
})();
tl;dr
What's a DRY way to set mulitple pages' document.domain
working with Rails?
回答1:
I think you're looking for Cross-Origin Resource Sharing (CORS). This allows javascript to make AJAX $.get/post
requests across different domains.
Here's a rails library to get you started: https://github.com/cyu/rack-cors#rails
You'll want to set the origins
property to be yoursubdomain.herokuapp.com
来源:https://stackoverflow.com/questions/35705950/dry-way-for-setting-document-domain-from-rails