Run script on web whatsapp - javascript

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.

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.)

Related

Javascript click on specific element always uses wrong/other element id

I have several html pages and each one has a varying number of buttons that appear based on the page's content.
In just Javascript (since I don't use jquery), I am trying to have the same few lines of code apply to the respective button that was clicked, with the exception that the id tag has to be 'concatenated' into a variable based on the respective button that was clicked.
I saw other solutions on here that cycled through the elements of the class (in this case the "zoom_buttonClass"). However, when I attempt this, regardless of number of buttons on the page or which button was clicked, it is always the LAST button in the list that seems to be the one seen as clicked.
I need to always check if buttons are clicked, but how do I apply the actions based on the ACTUAL button that was clicked?
My HTML and JS code snippets are below:
Thanks in advance.
HTML code:
<div class="modalClass" id="myModalID">
<span class="closeModalClass" aria-label="Close Photo Enlargement Modal Box">×</span>
<img class="modal_contentClass" id="modalEnlargementID">
</div>
<div id="captionID"></div>
JS code:
for (var i = 0;i < document.getElementsByClassName("zoom_buttonClass").length;i++){
document.getElementsByClassName("zoom_buttonClass")[i].addEventListener('click', myFunction
(var attribute = this.getAttribute("id");
var photoIDstring = "photo"+counterX+"ID";
document.getElementById('myModalID').style.display = "block";
document.getElementById('captionID').style.display = "block";
document.getElementById("modalEnlargementID").src = document.getElementById(photoIDstring).src;
captionText.innerText = document.getElementById(photoIDstring).alt;
), false);
};
Well, I started again and I think I may have hit upon a solution. It seems to work.
var captionText = document.getElementById("captionID");
var howManyButtons = document.getElementsByClassName("zoom_buttonClass").length;
var buttonCollection = document.getElementsByClassName("zoom_buttonClass");
for (let i=0; i < howManyButtons; i++) {
buttonCollection[i].onclick = function() {
let photoIDstring = "photo"+(i+1)+"ID";
document.getElementById('myModalID').style.display = "block";
document.getElementById('captionID').style.display = "block";
document.getElementById("modalEnlargementID").src = document.getElementById(photoIDstring).src;
captionText.innerText = document.getElementById(photoIDstring).alt;
}
}

Firefox blocks resource loading at self (“script-src”)

I'm trying to create a to-do extension for firefox and I need to trigger a function when the delete button is clicked (line 8).
function viewPrevious(){
var prom = browser.storage.sync.get(null);
prom.then((res) => {
var text = '<ul class="list-group list-group-flush">';
var i;
for (i = 0; i < res.todos.length; i+=4) {
text+='<ul class="list-group list-group-flush"><li class="list-group-item">'+res.todos[i]+' '+res.todos[i+1]+' '+res.todos[i+2]+'</li>';
text+='<button type="button" class="btn btn-primary" onClick="myFunc" id='+i+'">Delete</button>';
}
text+='</ul>';
document.getElementById("oldTodos").innerHTML = text;
window.onload=function(){
console.log("KKOO");
var promii = browser.storage.sync.get(null);
promii.then((res) => {
for(i=0;i<res.todos.length;i+=4){
console.log("redda");
document.getElementById(i.toString()).addEventListener('click',function(){
console.log('kjk'+i);
var removingItem = browser.storage.sync.remove(i);
removingItem.then(function(){
viewPrevious();
});
});
}
});
}
});
}
I have added the onClick="myFunc" in line 8 and the function is,
function myFunc(){
console.log("ABC");
}
when I run this and click the button it gives me the following error
Content Security Policy: The page’s settings blocked the loading of a resource at self (“script-src”). Source: onclick attribute on BUTTON element.
I tried using meta tags and giving script-src 'unsafe-inline', but it also did not work. And I dont have a good idea about this content security policy
Is there any another way for making this work or am I doing something wrong?
Your issue here is the HTML onclick attribute. To do this correctly, you need to use addEventListener like you are on the later click listener.
// Untested, but it should put you on the correct path
var ul = document.createElement('ul');
ul.classList.add('list-group', 'list-group-flush');
var i;
for (i = 0; i < res.todos.length; i+=4) {
// I'm ignoring <ul class="list-group list-group-flush"> from your example, because
// this doesn't look like you intend to be nesting lists
var li = document.createElement('li';
li.classList.add('list-group-item');
// In your example, you had left an open XSS vulnerability by simply
// concatenating user todos with your markup, textContent is much safer
li.textContent = res.todos[i]+' '+res.todos[i+1]+' '+res.todos[i+2];
ul.appendChild(li);
var button = document.createElement('button');
button.classList.add('btn', 'btn-primary');
button.addEventListener('click', myFunc);
button.id = i;
ul.appendChild(button);
}
document.getElementById("oldTodos").innerHTML = '';
document.getElementById("oldTodos").appendChild(ul);

Create multiple buttons in JavaScript

I have checked for syntax errors and it does seems like everything is okay, it just does not do anything when loading the body of the page. I know I have linked the script correctly to the html file, because I've already implemented a JS Clock which displays itself in the page as you can see in the pen. Is there anything wrong with my code? Why aren't my 10 buttons displaying? I fear Bootstrap may be preventing me from getting my buttons show up.
My purpose is to create 10 buttons, so that I don't have to write the same code 10 times.
The Codepen is just to check out my code, I work on Atom usually. This is my Codepen!
<div class="container-fluid" id="buttons">
</div>
function createButtons() {
for(i = 0; i < 11; i++) {
var button = document.createElement("<button type=\"button\" class=\"btn btn-outline-success\">Chapter[i]</button>");
var buttonDiv = document.getElementById("buttons");
buttonDiv.appendChild(button);
}
}
document.body.addEventListener("load", createButtons(), false);
The function createElement accept a tag name as argument.
var Chapter = [0,1,2,3,4,5,6,7,8,9,10];
for(i = 0; i < 11; i++) {
var button = document.createElement("button");
button.innerHTML = Chapter[i];
button.className = "btn btn-outline-success";
var buttonDiv = document.getElementById("buttons");
buttonDiv.appendChild(button);
}

Javascript onclick parameter

I have a question about "onclick" function in JavaScript. Here I have a div "InfoBar"
<div id="InfoBar"><br>
and two for loop
var src = new Array();
for(var i = 0; i < 2; i++){
src.push("el1","el2");
}
for(var j = 0; j < 2; j++){
doesFileExist(src[j]);
}
and a doesFileExist() and klick function
function klick(el){
alert(el)
}
function doesFileExist(urlToFile){
document.getElementById('InfoBar').innerHTML += '<br>' + '<a id="css" onclick="klick(urlToFile)" href="#" title="'+urlToFile+'">' + "link1 : " + urlToFile + '</a>';
}
now I've added a "onclick" function in "a href".
if I click on "link1:el1", I want to display as alert "urlToFile" string.
But I doesn't work.
In "a href" title="'+urlToFile+'" it works perfect, but in "onclick" doesn't work.
Can anyone help me?
Thanks in advance.
You are generating an attribute. That gets converted back into a function but the scope is broken.
Don't use intrinsic event attributes.
Minimise use of globals
Avoid generating HTML by mashing strings together (at best it is hard to read, at worst you get this sort of issue)
Use standard DOM:
var container = document.getElementById('InfoBar');
container.innerHTML = ""; // Delete any existing content
container.appendChild(document.createElement('br'));
var anchor = document.createElement('a');
anchor.setAttribute('id', 'css'); // You are running this function is a loop and creating duplicate ids. Use a class instead.
anchor.addEventListener('click', function (event) {
klick(urlToFile); // the local variable urlToFile is still in scope
});
anchor.setAttribute('href', '#'); // Why are you linking to the top of the page? Use a <button>
anchor.setAttribute('title', urlToFile);
anchor.appendChild(document.createTextNode("link1 : " + urToFile));
container.appendChild(anchor);
Event handles assigned this way won't work. You have to use JavaScript event handles. Means, you must create a new 'a' element, then bind a click event to it, and then append it as a child to the parent node. All this stuff is very good described on the web out there.

Get all buttons of a web page and delete the ones with certain background-image in Javascript

Good morning everybody, I'm a bit of newbie in javascript and other web languages.
What I want to do is get all buttons of a web page, then delete the one(s) with a specific background-image.
I understand the use of getElementsByTagName but can't do anything more.
I've started with the code above :
document.getElementsByTagName(button)
What should I do next please ?
Thanks for your help.
Just follow the steps :
Get all elements
Check each element with specific background-image
Remove the element.
HTML :
<div id="parentNode">
<button style="background-image:url('http://i.dailymail.co.uk/i/pix/2013/11/11/article-2500617-007F32C500000258-970_306x423.jpg')">First</button>
<button style="background-image:url('http://www.allgraphics123.com/ag/01/14142/14142.gif')">Second</button>
<button style="background-image:url('http://jitendravaswani.files.wordpress.com/2013/02/191356xcitefun-cartoon-pluto.jpg')">Third</button>
<button style="background-image:url('https://lh5.googleusercontent.com/-WsZ4Q7Y156A/AAAAAAAAAAI/AAAAAAAAABM/vN1-gy0xZQU/photo.jpg')">Fourth</button>
</div>
javaScript :
var imageButtons = document.getElementsByTagName("button");
var parent = document.getElementById("parentNode");
for(var index = 0; index < imageButtons.length; index++ ){
if(imageButtons[index].style.backgroundImage == "url(http://www.allgraphics123.com/ag/01/14142/14142.gif)"){
alert();
parent.removeChild(imageButtons[index]);
}
}
jsFiddle
Try this
<script type="text/javascript">
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].style.backgroundImage == "specific image") {
buttons[i].style.display = 'none';
}
}
</script>

Categories