Itay Alon Itay Alon - 7 months ago 45
Javascript Question

Run script on web whatsapp

I tried to run script with greasemonkey on web whatsapp. But not work so well.
the code need to open new windows and refresh it with content:

[1st part:]

var list = main[0].getElementsByClassName("msg");
var i;
for (i = 0; i < list.length; i++) {
list[i].innerHTML += '<button type="button" class="addButton" onclick="javascript:addNewMsg(this.parentElement)">Add</button>';
}


[2nd part:]

document.body.innerHTML += '<div style="position:absolute;bottom:20px;right:20px;z-index:80;border:1px black solid"><button type="button" id="startButton" onclick="javascript:us_openWAwindows()">Start</button></div>';


The button not working (not open new windows)..

Thx for the help.

edit: cleaned the code for presenting only the issue.

Answer

It would appear you can't use onclick attributes on this page due to its Content Security Policy.

Please try using event listeners you are attaching in JavaScript, not embedded JS code in HTML.

1) For creating the "Add" buttons it would probably be best to create it totally in JS and set all attributes there, because from first glace it looks to me like there can be multiple and you are creating and deleting them again depending on what the user does.

for (i = 0; i < list.length; i++) {
    var btn = document.createElement("button");
    btn.setAttribute("type", "button");
    btn.setAttribute("class", "addButton");
    btn.addEventListener("click", function() {
        addNewMsg(this.parentElement);
    });
    btn.innerHTML = "Add";
    list[i].appendChild(btn);
}

2) For the "Start" button which is created only once we can keep the HTML if you want and use its ID to reference it (although you could also use the same approach as I did above):

document.body.innerHTML += '<div style="position:absolute;bottom:20px;right:20px;z-index:80;border:1px black solid"><button type="button" id="startButton">Start</button></div>';
document.getElementById("startButton").addEventListener("click", us_openWAwindows);

(Note that I removed the onclick attribute from both.)

Comments