Getting content of a script file using Javascript

前端 未结 8 1197
谎友^
谎友^ 2021-02-07 19:38

I have the following script element in my web page:


Using JavaScript,

8条回答
  •  梦如初夏
    2021-02-07 19:53

    You could get the attribute of the src of the script and then use XHR to get the contents of the JS file. It's a much cleaner way of doing it IMO. e.g.:-

    if(window.XMLHttpRequest) {
                    var xhr = new XMLHttpRequest();         
                    xhr.onreadystatechange = function() {
                        if(xhr.status == 200 && xhr.readyState == 4) {
                            var sourceCode = xhr.responseText;
                                                alert('The source code is:-\n'+sourceCode);
                        }
                    }
                    xhr.open("GET",document.getElementById('scriptID').src,true);
                    xhr.send(null);
                }
    

提交回复
热议问题