Skip to content Skip to sidebar Skip to footer

A Issue When Inject A Javascript Code That Overrides The One Existing In Dom?

I have read this question Is it possible to inject a javascript code that OVERRIDES the one existing in a DOM? and the solution works well most of time, but sometimes, seems Java

Solution 1:

I found My injected <script> runs after the target-page's javascript, despite using run_at: document_start? which has pointed out the reason and gave a work-around solution.

But it is really difficult to write js code into a string like that. So I wrote a python code to read and generate them.

import sys

s_injector_header = """
function injectJs(text) {
    var scr = document.createElement('script');
    scr.type="text/javascript";
    scr.textContent=text;
    document.documentElement.appendChild(scr);
}

"""defopenInjector():
    fd = open(sys.path[0]+"/js_injector.js","w")
    fd.write(s_injector_header)
    return fd

defcloseInjector(fd):
    fd.close()

definjectJs(fd,filename):
    jsfd = open(sys.path[0]+"/"+filename,"r")
    text = jsfd.read()
    text = text.replace("\\","\\\\")
    text = text.replace("'","\\'")
    text = text.replace('"','\\"')
    text = text.replace('\n','\\n')
    fd.write("injectJs('"+text+"');\n\n")

defmain():
    fd = openInjector()
    injectJs(fd,"md5.js")
    injectJs(fd,"dessrc.js")
    injectJs(fd,"my_code.js")
    closeInjector(fd)

if __name__ == '__main__':
    main()

Solution 2:

The order of execution is certainly not random.

What your function injectJS is doing is creating a tag with a "src" field of my.js. Then injecting that into your HTML. Which means my.js is included asynchronously.

Here is what test.html sees:

<script src="my.js"></script>


Because of it being asynchronous, the contents of my.js are not always loaded when you want. To mitigate this issue, you do not want to include my.js, you want to include the contents of my.js.

Using Broswerify's brfs, you can put a require() statement into your browser side code and have it inject the actual file contents. After the right installs, your js_injector.js would need the following:

//js_injector.jsvar fs = require('fs');

functioninjectJs(link) {
    //Create script tag with full file content as the contentvar scr = document.createElement('script');
    link = fs.readFileSync(__dirname + '/inject.js', 'utf-8');
    scr.textContent = link;

    (document.head || document.documentElement).appendChild(src);
}

injectJs('my.js');

Which would give you the following and the behavior you expect:

//test.html

<script>console.log("in my.js");
    functionfoo() {
        console.log("in my.js foo");
    }
</script>

Post a Comment for "A Issue When Inject A Javascript Code That Overrides The One Existing In Dom?"