Search code examples
javascriptgetelementbyidwindow.open

GetElementById returning null on a new window


function wait(w, id) {
    while (w.document.getElementById(id) == null) {
        console.log('waiting');
    }
    return true;        
}

var openWindow = window.open("http://www.google.com/?gws_rd=ssl", width=200, height=400);
if (wait(openWindow, 'lst-ib')) {
    openWindow.document.getElementById('lst-ib').value = "test";
}

I'm trying to open a new window, and in that new window find an id and change the value. I just used google for testing and 'lst-ib' is the id of the search bar on it.

I know the wait() function is super inefficient and should never really be used, but I'm new to JS and couldn't find any other way, but it doesn't seem to be the problem.

I tried simply setting the value but that would always return an error saying that getElementById(...) is null

Also,

document.getElementById('lst-ib').value = "test";

works whenever entered into the console


Solution

  • You should read about the same origin policy which does not allow a window to access the contents of another window unless the "origins" (protocol, domain and port) are the same.

    If your other window is http://www.google.com and the window you are running this code in is not the same, then the browser will simply block your access. It will not let you see inside that other document.

    To accomplish a cross window exchange of information, you either need two cooperating windows using postMessage() or two windows with the same origin. There is no other workaround.

    And, yes you are correct that you should never use a polling loop like that. It will block that window's Javascript from doing anything else. If you absolutely must poll repeatedly, then you use setTimeout() or setInterval() to check over and over until some condition is true. This allows other scripts to run in that window while waiting for the condition to become true.