Search code examples
javascriptwindow.open

How can I run a script in another (newly-opened) tab?


I am trying to run a script in a new tab. The code I use is this:

$ = jQuery;
function openAndPush(url, id) {
    var win = window.open('https://example.com' + url + '?view=map');
    var element = $('<script type="text/javascript">console.log("Starting magic...");var region_id='+id+';$=jQuery;var p=$(\'div["se:map:paths"]\').attr(\'se:map:paths\');if(p){console.log("Found! pushing..."); $.get(\'https://localhost:9443/addPolygon\', {id: region_id, polygon: p}, function(){console.log("Done!")})}else{console.log("Not found!");}</script>').get(0);
    setTimeout(function(){ win.document.body.appendChild(element); 
    console.log('New script appended!') }, 10000);
}

Considering the following:

  • I was inspired in this answer, but used jQuery instead.
  • I run this code in an inspector/console, from another page in https://example.com (yes, the actual domain is not example.com - but the target url is always in the same domain with respect to the original tab) to avoid CORS errors.
  • When I run the function (say, openAndPush('/target', 1)) and then inspect the code in another inspector, one for the new window, the console message Starting magic... is not shown (I wait the 10 seconds and perhaps more). However the new DOM element (this script I am creating) is shown in the Elements tab (and, in the first console/inspector, I can see the New script appended! message).

(In both cases jQuery is present, but not occupying the $ identifier, which seems to be undefined - so I manually occupy it)

What I conclude is that my script is not being executed in the new window.

What am I missing? How can I ensure the code is being executed?


Solution

  • Instead of embedding script element in the document, do this.

    • wrap the code that you want to run in another tab, into a function.
    • bind that wrapped function to the new tab's window
    • Call that function

    Here's the code that I ran in my console and it worked for me i.e another tab was opened and alert was displayed.

    function openAndPush(url, id) {
        var win = window.open('https://www.google.com');
        win.test = function () {
            win.alert("Starting magic...");
    
        }
        win.test();
        setTimeout(function () {
            win.document.body.appendChild(element);
            console.log('New script appended!')
        }, 10000);
    }