OnClick event doesn't work in my chrome extension [duplicate] - javascript

This question already has answers here:
The Chrome extension popup is not working, click events are not handled
(2 answers)
Closed 5 years ago.
I have made a little extension which inserts buttons into the html page and I have inserted onClick events on each button, but when i press them they don't work. I have found some topics on this site and a guy was talking about addEventListener but i couldn't use it. My code is something like this:
var setButton = "<button type='button' id='setter2' onclick=Set_one(this.id)>set</button>";
var str = getRow.insertCell(-1);
str.innerHTML = setButton;

In Chrome extensions, inline code is forbidden. You cannot use onclick attribute at all for extension scripts, and CSP cannot be relaxed.
You will have to use addEventListener to make it work. It's not hard, and covered in the documentation linked above.
var setButton = "<button type='button' id='setter2' onclick=Set_one(this.id)>set</button>";
var str = getRow.insertCell(-1);
str.innerHTML = setButton;
document.getElementById("setter2").addEventListener("click", function() {
Set_one(this.id);
});
It's even better though if you don't use innerHTML assignment and directly create/append elements:
var setButton = document.createElement("button");
setButton.textContent = "set";
setButton.id = "setter2";
setButton.addEventListener("click", function() {
Set_one(this.id);
});
getRow.insertCell(-1).appendChild(setButton);

Related

add an event listener to an element with javascript [duplicate]

This question already has answers here:
Cross domain iframe issue
(5 answers)
Adding click event handler to iframe
(2 answers)
Closed 4 years ago.
Through a script tag I've inserted on an external site, I am trying to load in some javascript which iframes a widget I am hosting on a webpage,
I only want the small launcher icon iFramed initially and then when its opened, iFrame the entire chat window when it's expanded. As Iframing the whole thing takes up a lot of the external site and means everything behind is isnt reachable!
My thought was to have a small iframe initialy and then when it's clicked, increase it's size to the entire window and then while doing so, add an element in the area where the launcher is to then close it when pressed and reduce the iframe size again! hacky I know but i dont know how else I can do this?
What you can see is me creating an iframe, and trying to give it an id
of 'ifrm' with the line:
the code so far: ifrm.setAttribute("id", "ifrm");
. AND then try to change the iframes CSS or append a new one? BUT this doesnt call the function when clicked so i may
have the setting of the ID / calling it wrong?
Then how would I append an element? sorry ive probably gone the wrong way about this.
prepareFrame();
function prepareFrame() {
console.log("yes this consoles inside of prepareFrame")
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "https://5efae1b1.ngrok.io");
ifrm.style.width = "100px";
ifrm.style.height = "100px";
ifrm.style.position="fixed";
ifrm.style.right="0";
ifrm.style.bottom="0";
ifrm.style.border="0";
ifrm.setAttribute("id", "ifrm");
document.body.appendChild(ifrm);
document.getElementById("ifrm").addEventListener("click", function(){click1(1);}, false);
}
function click1() {
alert("calling");
document.getElementById("ifrm").style.backgroundColor = '#ff0000';
colorcheck = document.getElementById("ifrm").style.backgroundColor;
console.log('colour check' + colorcheck);
};
Thanks so much if you can help!
Instead of doing this:
document.getElementsByTagName("iframe")[0].setAttribute("id", "ifrm");
Try this at the beginning of your iframe creation:
var ifrm = document.createElement("iframe");
ifrm.setAttribute('id', 'ifrm'); // assign an id
add ifrm.contentDocument.addEventListener("click", function(e){click1(e)}, false) to inside the prepareFrame function, this will then call the click1 function.

Hide keystrokes from window-wide listeners

I'm making an extension for Chrome to be used on Youtube. The extension adds an overlay on top of the video with a text input. However, typing into the extension triggers Youtube's various keystroke listeners (e.g. space -> pause). event.stopPropagation() does nothing, neither does return false at the end of the Angular event callback.
My current (successfully prototyped but not yet implemented) solution is to wrap the input in an iframe, which will pass messages back to the parent window:
iframe.contentWindow.document.querySelector("#wrapped-input").addEventListener("input", function(){
result.innerHTML = this.value;
});
I feel that this solution is a bit of a hack, and I'm hoping to find something more elegant. As an aside, I am using AngularJS for the app, so if there are any Angular-specific workarounds, I'd love to know those too. Thoughts?
EDIT
Current solution:
<iframe id="wrapper-frame"></iframe>
...
link: {
var input = '<input id="inner-input" />';
var wrap = $window.document.querySelector('#wrapper-iframe').contentWindow.document;
$scope.commentInput = wrap.querySelector('#inner-input');
wrap.open();
wrap.write(input);
wrap.close();
$scope.commentInput.addEventListener('input', function(){
var val = this.value;
$scope.$applyAsync(function(){
$scope.inputContent = val;
});
});
}
It works, but still -- iframe. Bleh, hack. I will leave the question open in case if someone has a better idea.

Firefox extension to access DOM (with jQuery) [duplicate]

This question already has an answer here:
FireFox extension: How to access page element via jQuery?
(1 answer)
Closed 8 years ago.
I'm trying to manipulate the HTML of a page using my extension and jQuery.
In this simple test, I'm trying to first load jQuery and then replace all h1's to "Hello", like this: $("h1").html("Hello");
See this jsfiddle: http://jsfiddle.net/37vxJ/ (minus the jQuery part:)
var myExtension = {
init: function() {
// The event can be DOMContentLoaded, pageshow, pagehide, load or unload.
if(gBrowser) gBrowser.addEventListener("DOMContentLoaded", this.onPageLoad, false);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered the event
setTimeout(function(){
//alert("page is loaded \n" +doc.location.href);
$("h1").html("Hello");
}, 1000);
}
}
window.addEventListener("load", function load(event) {
//remove listener, no longer needed
window.removeEventListener("load", load, false);
myExtension.init();
},false);
How can I make this work?
If I uncomment: //alert("page is loaded \n" +doc.location.href);
The extension will print out the URL (after 1 second)
You are trying to use jQuery in the wrong context.
Change
$("h1").html("Hello");
to
doc.defaultView.wrappedJSObject.$("h1").html("Hello");
Use firebug. it is the best for me.
You can find it here:
https://addons.mozilla.org/fr/firefox/addon/firebug/
UPDATE:
There is a powerful service such as there is a reverse engineering to inspect DOM : Just , click on the blue arrow (mentionned on the picture) , Enter mouse on your Element ,And you will get a synchronization between the GUI and DOM .
Modern versions of Firefox have built in Console, Inspector, Debugger, Profile and Network tracking. Simplyn click on Menu->Developer and select the tool you need
Alternatively use Firebug as recommended in another answer.

function for dynamically created <a> tag is not working

i am working on a mobile website with html,js and css.i have created tag through HTML5 DOM & assigned functions to it. It's not working.
My html code(which i have tried thro' DOM method);
<script>
var addExhibits = document.getElementById('mycontent');
function mytest()
{
var div = document.createElement('div');
div.id = 'rateMe';
var anchor = document.createElement('a');
anchor.id="_1";
anchor.onclick = rateIt(this);
anchor.onmouseover=rating(this);
anchor.onmouseout=off(this);
div.appendChild(anchor);
addExhibits.appendChild(div);
}
</script>
<body><div id='mycontent' title="Rate Me..."></body>
Code(statically created tag - works fine)
<div id="rateMe" title="Rate Me...">
<a onclick="rateIt(this)" id="_1" onmouseover="rating(this)" onmouseout="off(this)"></a>
</div>
rate(this) is a function in external JS(http://reignwaterdesigns.com/ad/tidbits/rateme/)
Your event handler just assign the result of the respective function calls here:
anchor.onclick = rateIt(this);
anchor.onmouseover=rating(this);
anchor.onmouseout=off(this);
I assume you want them to execute in case of the event instead:
var that = this;
anchor.onclick = function(){ rateIt(that); };
anchor.onmouseover = function(){ rating(that); };
anchor.onmouseout= function(){ off(that); };
You don't call your mytest() function anywhere. That's the first thing I see. The other thing is that you are putting your script above your div (mycontent) so the div has not yet been created when your script is read. But I don't completely understand what your aim is here or what exactly your problem is.
You don't need to pass this.
you can access your element inside the function in many ways.
var addExhibits=document.getElementById('mycontent'),
rateIt=function(e){
e=e||window.event;
var target=e.target||e.srcElement;//polyfill for older browser
console.log(this,target);
},
rating=function(e){
console.log(this,e.target);
},
off=function(e){
console.log(this,e.target);
},
mytest=function(){
var div=document.createElement('div'),
a=document.createElement('a');
div.id='rateMe';
a.id="_1"; // id's shouldn't contain _ - & numbers(1st letter) even if it works.
a.onclick=rateIt;
a.onmouseover=rating;
a.onmouseout=off;
div.appendChild(a);
addExhibits.appendChild(div);
};
this way you also don't create memory leaks.
ps.: that external js example you using is written very bad.
to make your example work you need to change the strange me/num/sel variables in the external js with the proper one (this/e.target/e.srcElement).

How to set onClick with JavaScript?

I am trying to set the onclick event using javascript. The following code works:
var link = document.createElement('a');
link.setAttribute('href', "#");
link.setAttribute('onclick', "alert('click')");
I then use appendChild to add link to the rest of the document.
But I obviously would like a more complicated callback than alert, so I tried this:
link.onclick = function() {alert('clicked');};
and this:
link.onclick = (function() {alert('clicked');});
But that does nothing. When I click the link, nothing happens. I have testing using chrome and browsing the DOM object shows me for that element that the onclick attribute is NULL.
Why am I not able to pass a function into onclick?
EDIT:
I tried using addEventListener as suggested below with the same results. The DOM for the link shows onclick as null.
My problem may be that the DOM for this element might not have been fully built yet. At this point the page has been loaded and the user clicks a button. The button executes javascript that builds up a new div that it appends to the page by calling document.body.appendChild. This link is a member of the new div. If this is my problem, how do I work around it?
I have been unable to reproduce the problem. Contrary to the OP's findings, the line below works fine on the latest versions of IE, FF, Opera, Chrome and Safari.
link.onclick = function() {alert('clicked');};
You can visit this jsFiddle to test on your own browser:
http://jsfiddle.net/6MjgB/7/
Assuning we have this in the html page:
<div id="x"></div>
The following code works fine on the browsers I have tried it with:
var link = document.createElement('a');
link.appendChild(document.createTextNode("Hi"));
link.setAttribute('href', "#");
link.onclick= function() {link.appendChild(document.createTextNode("Clicked"));}
document.getElementById("x").appendChild(link);
If there is a browser compatibility issue, using jQuery should solve it and make code much much more concise:
var $link = $("<a>").html("Hi").attr("href","#").click(function (){$link.html("Clicked")})
$("#x").html($link)
If brevity is not a strong enough argument for using jQuery, browser compatibility should be ... and vise versa :-)
NOTE: I am not using alert() in the code because jsFiddle does not seem to like it :-(
If you're doing this with JavaScript, then use addEventListener(), with addEventListener('click', function(e) {...}) to get the event stored as e. If you don't pass in the event like this, it will not be accessible (although Chrome appears to be smart enough to figure this out, not all browsers are Chrome).
Full Working JSBin Demo.
StackOverflow Demo...
document.getElementById('my-link').addEventListener('click', function(e) {
console.log('Click happened for: ' + e.target.id);
});
Link
You can add a DOM even listener with addEventListener(...), as David said. I've included attachEvent for compatibility with IE.
var link = document.createElement('a');
link.setAttribute('href', "#");
if(link.addEventListener){
link.addEventListener('click', function(){
alert('clicked');
});
}else if(link.attachEvent){
link.attachEvent('onclick', function(){
alert('clicked');
});
}
Setting an attribute doesn't look right. The simplest way is just this:
link.onclick = function() {
alert('click');
};
But using addEventListener as JCOC611 suggested is more flexible, as it allows you to bind multiple event handlers to the same element. Keep in mind you might need a fallback to attachEvent for compatibility with older Internet Explorer versions.
Use sth like this if you like:
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>

Categories

Resources