Running Javascript in new window.open

前端 未结 4 1928
执念已碎
执念已碎 2020-12-01 22:10

I\'m running this function to open a new window.

function htmlNewWindow(id) {
    var html = $(id).html();
    var newWindow = window.open(\'\');
    newWind         


        
4条回答
  •  粉色の甜心
    2020-12-01 22:39

    Here's how you create, and then append a script file within a new window:

    var fileref = document.createElement('script');
    //creates script in current document
    fileref.setAttribute("type", "text/javascript")
    //set it to JS by "type"
    fileref.setAttribute("src", filename)
    //set your "src=yourFile_href_Here.js" 
    
    
    //Then create your newWindow as you did above, but slightly updated
    //Create your function which will consume the "fileref" argument
    function htmlNewWindow(fileref) {
        var newWindow = window.open('');
        newWindow.document.getElementsByTagName("head")[0].appendChild(fileref);
    }; //right now the function is made but you still have to execute it
    
    //Execute your function, and pass it the variable "fileref" that you set above.    
    
    htmlNewWindow(fileref);
    //Within this edit you will append the head element
    //with your newly created script(or any other parameterized argument)
    
    /* Replace your filename to pass any other script */
    

    NOTE - Opening a page residing on a different domain, if not specifically allowed, will reject instances of this due to CORS(https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)

    It's not a safe practice to be sending your scripts into other people's pages or allowing them in your own if your domain hasn't sent them. Also, depending on your server/technology stack you may need to configure your *-origin settings within your backend stack. See here: (https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)

提交回复
热议问题