I've looked at I can't find a suitable solution.
When you right-click and view the HTML source, then click on the link to a JavaScript (.js) file, the file loads and displays the code.
I want to prevent this. It's been a while but I know you can check to see where it's being called and prevent it from opening if it's not called locally, i.e., on the domain where it lives, but I can't remember how.
CodePudding user response:
This is not possible. If your code is not sent to the client, then the client won't have any code to run, and anything sent to the client can be read by the user. Even if you found a way for the browser to hide it, a technologically knowledgeable user can just use cURL to see the source.
So there is no way to hide code from the user, but you can very easily make it much harder to understand. The most common way of doing this is to obfuscate the code or make it so convoluted and ugly that it would take a while for someone to understand what it exactly does. This is not just minifying the code and making it look ugly, this is using a completely different way of doing the same thing. For example, take this input code:
a = 1;
b = 2;
console.log(`${a} ${b} = ${a b}`);
run it through this online obfucator and get this result:
function _0x1450(_0x197943,_0x16e058){var _0x551a06=_0x551a();return _0x1450=function(_0x14505a,_0x1c7cf5){_0x14505a=_0x14505a-0xca;var _0xf62bf8=_0x551a06[_0x14505a];return _0xf62bf8;},_0x1450(_0x197943,_0x16e058);}function _0x551a(){var _0x34958f=['373970NKtNQT','8pCfaUJ','\x20 \x20','4413552ZtbXUP','339267FzcTIn','542560KzWApk','21632xuvhlJ','10518057bZIWFW','1694pVgAOK','\x20=\x20','1622674nEQaGr'];_0x551a=function(){return _0x34958f;};return _0x551a();}var _0x328ff8=_0x1450;(function(_0xb3255b,_0x38cc1a){var _0x317b39=_0x1450,_0x1f62b4=_0xb3255b();while(!![]){try{var _0xaf9fd=parseInt(_0x317b39(0xd4))/0x1 -parseInt(_0x317b39(0xce))/0x2 -parseInt(_0x317b39(0xd3))/0x3 parseInt(_0x317b39(0xd0))/0x4*(-parseInt(_0x317b39(0xcf))/0x5) -parseInt(_0x317b39(0xd2))/0x6 parseInt(_0x317b39(0xcc))/0x7*(parseInt(_0x317b39(0xca))/0x8) parseInt(_0x317b39(0xcb))/0x9;if(_0xaf9fd===_0x38cc1a)break;else _0x1f62b4['push'](_0x1f62b4['shift']());}catch(_0x5453e4){_0x1f62b4['push'](_0x1f62b4['shift']());}}}(_0x551a,0x87bdb),a=0x1,b=0x2,console['log'](a _0x328ff8(0xd1) b _0x328ff8(0xcd) (a b)));
Does that code make sense to you? Me neither. Does it run? Yes.
It should be noted that code can and has been de-obfuscated, however, it is a laborious task.