0

Currently in my index.html file I have the following script line:

<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&libraries=places"></script>

Is it possible to extract the src variable and import it in the script as a variable? I tried using xsl:variable located in an external variable.xsl file such as this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:variable name="google" select="API_KEY"></xsl:variable>

</xsl:stylesheet>

And then trying to import it into my script,

<xsl:include href="variable.xsl"/>
<script src="{$google}"></script>

But even when the xls:variable is in the same file, the script source doesn't work.

I would like to push my code to a public repo, which is why I'd like to hide the key.

6
  • You changed the title just now.. Is your goal still to hide the key? You don't really have to. Commented Feb 13, 2019 at 21:00
  • Is there a reason you're using XSL? You don't have that in your tags, so it's a bit confusing to see it in the question. As far as getting a parameter from a url, there's get javascript url parameter from script source file in HTML. Commented Feb 13, 2019 at 21:04
  • @HereticMonkey no real reason as to why I am using XSL. Just something I was trying, willing to try anything else. Commented Feb 13, 2019 at 21:12
  • @LucaKiebel Yes, my goal is to hide the key, but thought that I can get a more generic title Commented Feb 13, 2019 at 21:12
  • Possible duplicate of get javascript url parameter from script source file in HTML Commented Feb 13, 2019 at 21:13

2 Answers 2

1

Hope this is the answer you are looking for, by simply using JQuery you could add the src attribute dynamically

HTML

<script id="googleAPI">

Notice we set an id on the script element

Javascript

let url = "https://maps.googleapis.com/maps/api/js?key=MY_KEY&libraries=places"
$("#googleAPI").attr("src", url)
Sign up to request clarification or add additional context in comments.

Comments

1

You cannot hide something client side, only obfustucate it (make it harder to see). If you use the xsl file, I can make a request and see that, if you set the dynamically create the script, I can open the network tab see where the request is going. If you want to hide the key:

  • make a request from your own server to "https://maps.googleapis.com/maps/api/js?key=MY_KEY&libraries=places"
  • get the content as text/plain or convert it to dataURl and then send it to client side where you create a script tag and set the textContent, innerHTML, or create an object url from Blob (having the server response as Blob part) and set src etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.