Skip to content

Instantly share code, notes, and snippets.

@skojin
Created February 1, 2011 20:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skojin/806550 to your computer and use it in GitHub Desktop.
Save skojin/806550 to your computer and use it in GitHub Desktop.
respond_to_parent as single helper withot respond_to, works with rails3
# more simple version of https://github.com/itkin/respond_to_parent.git without dirty hacks that works good in rails3
# usage:
# in controller#create append render :layout => false
# in create.html.erb
# <%= eval_javascript_in_parent(<<EOF
# $('#entries-list').prepend('#{escape_javascript(render @entry)}');
# EOF
# ) %>
#
# most source from https://github.com/itkin/respond_to_parent/blob/master/lib/responds_to_parent.rb
module EvalJavascriptInParentHelper
# Executes JavaScript in the context of the parent window.
# Use this method of you are posting a form to a hidden IFRAME or if you would like
# to use IFRAME base RPC.
def eval_javascript_in_parent(script)
# Escape quotes, linebreaks and slashes, maintaining previously escaped slashes
# Suggestions for improvement?
script = (script || '').
gsub('\\', '\\\\\\').
gsub(/\r\n|\r|\n/, '\\n').
gsub(/['"]/, '\\\\\&').
gsub('</script>','</scr"+"ipt>')
# Eval in parent scope and replace document location of this frame
# so back button doesn't replay action on targeted forms
# loc = document.location to be set after parent is updated for IE
# with(window.parent) - pull in variables from parent window
# setTimeout - scope the execution in the windows parent for safari
# window.eval - legal eval for Opera
"<html><body><script type='text/javascript' charset='utf-8'>
var loc = document.location;
with(window.parent) { setTimeout(function() { window.eval('#{script}'); if (typeof(loc) !== 'undefined') loc.replace('about:blank'); }, 1) };
</script></body></html>".html_safe
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment