Reputation: 155
I'm creating a Plugin that any website could embed and display, similar as Disqus. I already have a pretty good idea and understanding on how it works on the client side thanks to this post: How to make a javascript like Disqus or IntenseDebate.
So the code I'm planning to use on the client side is similar with Disqus or Google Analytics:
<script type="text/javascript">
var user_id = 'anbmDj3ish43';
(function() {
var plug = document.createElement('script'); plug.type = 'text/javascript'; plug.async = true;
plug.src = 'http://www.example.com/user/' + user_id;
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(plug);
})();
</script>
For each page of the website The plugin displayed will be different so I need to change the content of the javascript code returned to the page (i.e. have to change the injected code, the design of the plugin,etc.). I use JAVA and Spring framework for the back-end since the rest of the application use these technologies.
So my question is the following: Inside my spring controller, what do I have to do to be able to return a javascript that will be understood by the browser? Or, I might be also on the wrong way and have to handle it a different way?
Below was one of my first guess but it sends back text/plain and it's not understood by the browser as javascript..
@Controller
@RequestMapping(value = {"/user/"})
public class EmbedJavascriptController extends AbstractController{
@Autowired
private Service service;
@Transactional
@RequestMapping(value = "/{userId}", method = RequestMethod.GET, produces="text/javascript; charset=utf-8")
public String home(HttpServletRequest request,HttpSession session,
@PathVariable("userId") String userId) throws Exception {
return "console.log('I wanna load some scripts');";
}
}
Any help would be appreciated :D
Upvotes: 0
Views: 7549
Reputation: 36
I had the same issue and resolved it using this technique.
You can return a ModelAndView which resolves to a JSP
using a InternalResourceViewResolver
. Your JSP
could hold all of your javascript
contents that you want to return. Add this line to the top of that JSP
.
<%@ page language="java" contentType="application/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
Upvotes: 2