Curtis Banks
Curtis Banks

Reputation: 362

How to replace Google Map Key generated by JAVASCRIPT script in DJANGO by a custom variable

I am trying to find a way to hide my google map key displayed on the javascript script.

The key is generated from django settings.

I am not sure how to properly achieve it with javascript script and src

settings.py

GOOGLE_MAP = "XZZZZZZX"

views.py

def foo_list(request):
    """
    Render list of foo.
    """
    foo = Foo.objects.all()

    # Google Map Key
    google_map_key = settings.GOOGLE_MAP

    context = {
            'foo': foo, 
            'google_map_key': google_map_key
            }

    return render(request, 'snippet/index.html', context)

HTML

{% extends "base.html" %}
{% load static %}


{% block content %}
    <!-- Render Map on HTML -->
    <div id="map"></div></br></br>

    <!-- Pass the Google Map key variable to Front end -->
    <div id="google_map" style="display:none" value="{{ google_map_key }}"></br>

{% endblock %}



{% block key %}
     <!-- Grab the Google Map key value from HTML above -->
     var name_ = document.getElementById('google_name').getAttribute("value");
    
     <!-- Google Map Key -->
    <script id="name" data-name="value" src="https://maps.googleapis.com/maps/api/js?key=XZZZZZZX&callback=initMap" async defer></script>

{% endblock %}

How can I possibly replace the google map key with the custom variable from the backend?

Upvotes: 0

Views: 69

Answers (1)

Pieter Steyn
Pieter Steyn

Reputation: 501

There are some tricks one can use to make it harder for someone to view javascript code, but there is no way for someone to definitively and completely hide javascript code.

The only way you can protect your API key is to go to your developers console and add application restrictions. An application restriction controls which websites, IP addresses or applications can use your API key.

Upvotes: 2

Related Questions