简体   繁体   中英

How to protect my Javascript from being accessed by other parties?

Simply put, I have a website with a Javascript library which includes ads through a script tag. Now I'm concerned that the implemented ads can access my Javascript library (also included through a script tag), which does Ajax calls to a server (on which the user has a session).

I am looking to guard my Javascript from influence of included Javascript of the ads, as I don't want the ad companies to be able to make Ajax calls. In doing this, I don't want to rely to serverside scripting outside my Javascript library (note that calls to the library cannot have serverside scripting) (although setting a htpasswd is possible ie).

An example would be:

Library.js (can have serverside scripting, an other domain)

var library = function(parameters) {
      return ajaxCallWithParameters(parameters);
}

Website Javascript: (cannot rely on serverside scripting)

toTable(library());

Included possibly malicious ads: (other domain)

sendToAdServer(library());

In the case of using serverside scripting I could simply do:

   <script>var <?php echo $somehowSyncedrandomByTime; ?> = function(parameters) {
          return ajaxCallWithParameters(parameters);
    }</script> <!-- included JS script of other domain which supplies AJAX -->

    <script>toTable(<?php echo $somehowSyncedrandomByTime; ?>());</script> <!-- current domain -->

    <script>sendToAdServer(???());</script> <!-- by including offsite ad script -->

This way, the ads cannot find the function in question. But the website cannot include serverside scripting, so I am looking for an alternative.

Is it possible to obscure my Javascript in a way that included Javascript from third parties cannot call/read it?

Frankly, no, it's not possible to somehow obscure or protect your scripts against other scripts running in the same context/scope as yours. But you always have the possibility to lock third party scripts in an iframe - ie, they won't be able to interact with your code in any way unless you provide an interface (eg social networks use this a lot).

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