The method discussed in this article has not been applied in actual projects, because I have not encountered projects that require this, but the experiment found it feasible.
1. Source of my thoughts
JavaScript is a good thing. Its appearance makes web pages more lively. Of course, the benefits are not just that. The popular AJAX applications in recent years have made people begin to pay more attention to the application of JavaScript small language (many program experts do not regard it as a language, at most it is a script title, and even look down on people who make scripts). Now many blogs open script permissions on official websites, allowing users to customize scripts to enrich their space, especially some technical professional blogs, which provide a rather relaxed development environment. But we also found that many blogs have restrictions on certain scripting methods. Note that I am talking about partial restrictions here. If it is all restrictions, it is very simple. Just filter out the <script> script block, but how do some restrictions be achieved?
Because I didn't encounter such a problem in my previous projects, I didn't do much in-depth research. At the beginning, I just thought of using the "replacement" method based on my feelings. Obviously this method doesn't work because it may go wrong. For example, if I want to disable the alert method, the following code is available:
window.alert('Some message');
Now to make the above code invalid, just let alert change it. For example, change it to capital ALERT, which will definitely report a script error, but you can still use try{}catch{} to include ALERT, but this is another big problem for the recognition of disable language packages, and there will be such an error: replace alert in document.write('alert some message');
Later I thought of rewriting the method, rewriting the method to be disabled, and making it do nothing. The result proved to be feasible, but I don’t know if it is a scientific method. I will take it out and discuss it with you.
2. Specific implementation
Let’s first look at the following code to disable the two methods “alert” and “write”:
window.alert=function(){}document.write=function(){}window.alert('Alert some message');document.write('Write some message');It seems really simple. In actual application, extract the first two lines separately and store them in an external JS file, and load the JS file first on the page that needs to filter JavaScript methods (you can also load this script on the previous line of the user editing content block, so that our administrator or web page maker can still use the method that will be disabled in the previous HTML block). In this way, calling the disabled method afterwards will not work.
Note: Finally, I would like to remind you that you should also disable some DOM operation methods, such as the remove() method, because users can use the DOM operation methods to remove the JS file you loaded at the beginning.