Browser: Google Chrome (Win 10x64)
This is the first time I am using the postMessage
API of javascript hence I am not aware of all of its nuances.
I am trying to loop over a set of DOM elements and then open up a bunch links in different tabs. Once those tabs are open find certain elements in their respective DOMs and display them via postMessage()
in the main windows.
The problem is that even though I have several tabs open, I only get information from the last tab.
Here is my code:
Prepare
postMessage()
listener on main window:window.addEventListener('message', (event) => { console.log(event.data); }, false);
Create my tabs array and get my DOM elements:
alert_list = document.querySelectorAll("tr.expand.alerts-table-tablerow");
var newTabs = [];
Loop over DOM elements, open tabs, add JS code that calls back to main window with the required data. This is where the main work happens:
alert_list.forEach((currentValue, currentIndex) => { alert_status = currentValue.childNodes[13].innerText; if(alert_status == "Enabled") { console.log(currentValue.childNodes[3].innerText + " " + currentValue.childNodes[7].innerText); newTabs.push(window.open(currentValue.childNodes[5].children[0].href, "_blank")); newTabs[newTabs.length - 1].onload = function() { setTimeout(((tab_element) => {return () => { window.parent.postMessage(tab_element.document.querySelectorAll("h1.search-name.section-title.search-title-searchname")[0].innerText); }})(newTabs[newTabs.length - 1]), 120*1000); }; }
} );
Now I keep getting information from the last tab that is opened multiple times. Precisely the number of tabs that are open. This lead me to believe that the problem was with javascript doing a late binding on the setTimeout
callback, hence I changed it to the following inspired by this:
((tab_element) => {return () => {
window.parent.postMessage(tab_element.document.querySelectorAll("h1.search-name.section-title.search-title-searchname")[0].innerText);
}})(newTabs[newTabs.length - 1])
This actually performs a closure of the actual DOM element I want. But it still does not work.
What am I doing wrong ?
Let me know if any other info is required.
Thanks.