How do you disable elements using JavaScript
What do you mean when you say: «disable script tags»? Disable how and why? What do you want to achieve?
Related: Use JavaScript to prevent a later tag from being evaluated? Btw, getElementsByTagName returns a NodeList . If you wanted to assign properties to elements, you’d have to iterate over the list first. Which attributes are supported by the script can be found in the specification.
@FelixKling : I will keep that in mind, Sir. I’m a JS noob. I still haven’t really got the hang of it. Thanks for the tip! +1 for the specs.
6 Answers 6
In fact, it is possible to disable execution by changing «type» attribute:
But if it’s executed it won’t be executed again anyway. So no need to disable it in this case. If it has added an event listener, or you did setInterval() in it — surely those won’t be disabled even if you delete
This seems quite useful for user generated or embedded HTML that is rendered and displayed after the main page load.
Can’t be done. A script tag evaluates as soon as the DOM renderer renders it, so getting a handle on it after wards won’t do much.
You can disable a script element. There are a couple of ways:
You can specify a different script type as other have listed. Heres the one that worked for me:
//loop through all script tags on page $('script').each(function()< var scripthtml = $(this).html(); $(this).replaceWith(''); >);
All of the official script types can all be found here: iana.org
The second way is just a simple if statement:
//loop through all script tags on page $('script').each(function()< var scripthtml = $(this).html(); $(this).replaceWith('if (1==0) '); >);
The if statement will always be false, so anything inside the script tag won’t execute. However all of your functions() inside the script tag will all be valid.
Heres the javascript equivalent of replaceWith:
//get script and html var yourscripttag = document.getElementById('yourscripttagID'); var scripthtml = 'if (1==0)'; //remove script yourscripttag.remove(); //create new script element var newscript=document.createElement('script'); newscript.type='text/javascript'; //insert html in new script tag newscript.appendChild(document.createTextNode(scripthtml)); //insert new script tag into head document.getElementsByTagName('head').item(0).appendChild(newscript);
JavaScript: Прячем скрипт от посторонних глаз
Хотелось ли Вам когда-нибудь спрятать от посторонних людей на своей страничке скрипт, который реализует нереально красивое появление меню или выполнение других действий, которые Вы бы не хотели видеть в скором времени на каждом втором сайте?
Если да, то способ изложенный в этой статье Вам пригодится совместно с обфускацией кода. При этом оговорюсь сразу, что способ не 100-процентный, но от большинства непрофессионалов и части профессионалов он возможно защитит.
Теория
- Загрузка скрипта непосредственно размещенного на странице или подгруженного с помощью DOM;
- Просмотр скрипта в окне Исходный код страницы;
- Сохранение страницы со всеми файлами на жесткий диск;
- Ввод прямого URL в адресной строке.
Практика
nojs.php
Найди JS Через 10 секунд Вы должны увидеть работу скрываемого скрипта в виде аллерта нажмите ссылку после алерта, дабы убедиться что события тоже не отвалились. По этой ссылке можно увидеть скрываемый скрипт
script1.php
Его задача: динамически загрузить script2.php, если есть заголовок referer. Таймауты можно уменьшить, в зависимости от примерного времени выполнения скрываемого скрипта.
script2.php
Итоги
- Переход по ссылке прямо ведущей на script2.php и расположенной на странице нашего сайта;
- Формирование http-запроса с указанием в нем заголовка referer.
- С помощью mod-rewrite заменять идущие к серверу script1.js и script2.js на script1.php и script2.php соответственно, чтобы на странице были всем привычные файлы js, так как php резко бросается в глаза;
- Сделать фиктивный скрипт максимально сложным, правдоподобным и запутанным, чтобы человек пытающийся его разобрать изрядно помучался перед осознанием того, что его обманули;
- Обфускация кода.
hide javascript/jquery scripts from html page? [duplicate]
How do I hide my javascript/jquery scripts from html page (from view source on right click)? please give suggestion to achive this . Thanks.
6 Answers 6
You can’t hide the code, JavaScript is interpreted on the browser. The browser must parse and execute the code.
You may want to obfuscate/minify your code.
Keep in mind, the goal of JavaScript minification reduce the code download size by removing comments and unnecessary whitespaces from your code, obfuscation also makes minification, but identifier names are changed, making your code much more harder to understand, but at the end obfuscation gives you only a false illusion of privacy.
this answer is much more fair than the winner one. is just it: you can not hide the code, web tools are able to see anyhow the scripts because at least one they are downloaded and executed. This was what i was looking for. thanks
Your best bet is to either immediately delete the script tags after the dom tree is loaded, or dynamically create the script tag in your javascript.
Either way, if someone wants to use the Web developer tool or Firebug they will still see the javascript. If it is in the browser it will be seen.
One advantage of dynamically creating the script tag you will not load the javascript if javascript is turned off.
If I turned off the javascript I could still see all in the html, as you won’t have been able to delete the script tags.
Update: If you put in then you won’t see the javascript but you do see the javascript file url, so it is just a matter of pasting that into the address bar and you d/l the javascript. If you dynamically delete the script tags it will still be in the View Source source, but not in firebug’s html source, and if you dynamically create the tag then firebug can see it but not in View Source.
Unfortunately, as I mentioned Firebug can always see the javascript, so it isn’t hidden from there.
The only one I haven’t tried, so I don’t know what would happen is if you d/l the javascript as an ajax call and then ‘exec’ is used on that, to run it. I don’t know if that would show up anywhere.
How to hide the ‘script’ HTML tag?
I am using HTML, and I’d like to hide the script tag from the user’s view. When the user views the page source, the definitions should not appear. How do I accomplish this?
Example
these things do not appear unless you see the source code. and hiding source code is not possible (you can reduce the code by doing most of the things in backend but you can’t eliminate it)
5 Answers 5
You cannot hide HTML. If you want a closed-source solution, use a proprietary format, such as Flash or Flex.
You can, however, obfuscate your JavaScript code (you should shrinkwrap or minify it anyhow) which makes reading it harder.
any code that executes client-side is by definition accessible to the computer which executes it — it’s like asking how to make a raspberry with flammable juice. It simply cannot be done. (disclaimer: I am not a genetic biologist, but I feel pretty good about that statement.)
You can limit it to one script tag by making an include file that references the other scripts..
You could also write script directly into the DOM. This also does not eliminate it (and the script to write the script would be there), but the user would have to use a DOM inspector (e.g. Firebug) to see it; it wouldn’t be visible via ‘view source’.
As others have said, this is just obfuscation, and simply kicks the problem down the road.
It reads to me like he’s wanting to completely eliminate it, not obfuscate it.
With that said, option #2 is to not use includes, and put obfuscated javascript in his HTML.
In my last answer I misunderstood what you meant by hiding the code.
Well as our other friends said there is no way to hide Scripts from source code.
But if you are afraid of people who want to steal your codes you can simply code your javascript instead of hiding it.
If you need a tool to code your Javascript you can use: Shell Tool Online
And feel safe to add your scripts. If anyone try to copy your scripts, they will get nothing.
How do I hide javascript code in a webpage?
Is it possible to hide the Javascript code from the html of a webpage, when the source code is viewed through the browsers View Source feature? I know it is possible to obfuscate the code, but I would prefer it being hidden from the view source feature.
Why would you want to hide Javascript? It’s not like you’d ever put any sensitive data that you don’t want the user finding in it. Right?!
@PaulPRO has a good point — why would you want to hide JavaScript? Anyone who wants to know what you’re doing is ALWAYS going to be able to get your script with a few keystrokes. They won’t just rely on View-Source. Anyone who doesn’t know how to get a script is likely not going to be interested in it anyway.
@UdayHiwarale It is very easy to see what are the GET and other HTTP queries performed by the client (just open the dev console and go to the network tab). When developing a website, you should assume on the server that all requests are forged by an attacker — and therefore you must validate all data, and carefully escape every string which you splice into SQL or other code.
12 Answers 12
I’m not sure anyone else actually addressed your question directly which is code being viewed from the browser’s View Source command.
As other have said, there is no way to protect JavaScript intended to run in a browser from a determined viewer. If the browser can run it, then any determined person can view/run it also.
But, if you put your JavaScript in an external JavaScript file that is included with:
tags, then the JavaScript code won’t be immediately visible with the View Source command — only the script tag itself will be visible that way. That doesn’t mean that someone can’t just load that external JavaScript file to see it, but you did ask how to keep it out of the browser’s View Source command and this will do it.
If you wanted to really make it more work to view the source, you would do all of the following:
- Put it in an external .js file.
- Obfuscate the file so that most native variable names are replaced with short versions, so that all unneeded whitespace is removed, so it can’t be read without further processing, etc.
- Dynamically include the .js file by programmatically adding script tags (like Google Analytics does). This will make it even more difficult to get to the source code from the View Source command as there will be no easy link to click on there.
- Put as much interesting logic that you want to protect on the server that you retrieve via AJAX calls rather than do local processing.
With all that said, I think you should focus on performance, reliability and making your app great. If you absolutely have to protect some algorithm, put it on the server, but other than that, compete on being the best at what you do, not by having secrets. That’s ultimately how success works on the web anyway.