简体   繁体   中英

What is the best way to configure Javascript from third-party site's script/include tag?

tl;dr: Is it safe/wise to use dynamic view engine such as Sinatra+ERB to dynamically generate javascript files with custom content for embedding on third party sites?

And specifically is it safe/wise to use that server-side view engine to embed those data as variables on the javascript page?

Full story:

I have javascript/Sinatra application that functions a little like Google Analytics, in that partner sites include our javascript file, and that JS code sends data to our Sinatra app.

I want to make it easy for our clients to configure this javascript include, since there is state data (like their customer ID and the user ID that is currently logged in) that they need to communicate to our javascript code. However, the data they need to communicate must be translated via our server-side database before our script can use it.

My current method feels a little hacky: Sinatra serves a dynamic javascript file as a "view". The client includes that file with a script tag such as:

<script src="/dynamic-js/include.js?client_key=xyz&user_key=abc">

On Sinatra's side, it gets those parameters, uses a database to convert them to internal values and then serves a dynamic (erb) javascript file with code like:

window.ourInternalVars = {};
window.ourInternalVars.client_int_key="<%=client_int_key%>";
window.ourInternalVars.user_int_key="<%=user_int_key%>";

My question is whether this is a "bad" solution (one likely to yield undesirable and/or unexpected outcomes) and/or whether there are "better" approaches (broadly used approaches, ones using existing libraries, or following community/industry best practices) to this problem?

I could obviously solve this problem with a static javascript file that reads its own URL parameters and makes an ajax call to configure itself, but that is slower (the data aren't present when the script begins) and so less useful for our purposes (it's also less reliable).

We could also ask our clients to make ajax/api calls to our server to do the conversion, but that makes the installation of our script more complex for them, and we want to make it as simple as possible for them (a one line script tag if possible).

Am I likely to regret the above strategy later or does this seem like a reasonable approach to managing dynamic third-party inputs/configuration to a javascript include?

Note also I've simplified the use-case above to make the question more clear.

If you properly escape the values, it looks fine to me.

Maybe the people at Code Review have more tips. Stack Overflow is for when your code doesn't work as desired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM