How to tell if a popup will get blocked - javascript

I appreciate how browsers work when deciding whether a window.open() was triggered by a click, as in, its only allowed when it came from a real element click event.
I want to write the same logic myself, how do I do that?
Say I have any JS function, called potentially anywhere and everywhere from the rest of my application, sometimes with a click event handler at the start of the callstack and some times not. How can I know this inside my method, without explicitly passing information about the start of the stack (click vs not) all the way around my application?
function iNeedToKnowIfStackFrame0WasAClickEventListener() {
var wasAClick = ???;
if(wasAClick)
window.open(...);
else
something.else();
}

You can get the event information using this.event.type.
You can either pass the event into the function like so:
function iNeedToKnowIfStackFrame0WasAClickEventListener(event) {
var wasAClick = event.type == "click";
if(wasAClick)
window.open(...);
else
something.else();
}
or you can get the event off this
function iNeedToKnowIfStackFrame0WasAClickEventListener() {
var wasAClick = this.event.type == "click";
if(wasAClick)
window.open(...);
else
something.else();
}

Related

How to get URL of an image in JavaScript?

I'm developing a Chrome extension, and I'm adding an onmouseover handler to each of the images on a page. When the user mouses over an image, it's URL should be stored in a variable. I know I can easily get the value of the src attribute of the image, but I want the full URL. The src attribute stores the path of the image on the server. For example, when you right click an image in Google Chrome, you get the "Copy Image URL" option, which copies the image's URL to the clipboard.
Is there any way to achieve this? Thanks.
Instead of imageElement.getAttribute("src") or $("img.something").attr("src"), which reads the original markup, use imageElement.src property which will always give you the full URL.
var imgFullURL = document.querySelector('img.something').src;
or:
var imgFullURL = $('img.something')[0].src;
To extract host name, path name etc. - parse the url with URL() constructor, which works in modern browsers or use the legacy method via creating a temporary a node.
You can use window.location to get the page you are currently on and the following will give you the URL parts you need:
window.location.protocol = "http:"
window.location.host = "stackoverflow.com"
window.location.pathname = "/questions/32828681/how-to-get-url-of-an-image-in-javascript"
So, likely, you will need protocol, then "//", then host and finally the image src.
So the TL;DR is this:
(function() {
const imageInfo = new Object();
imageInfo.source = '';
window.addEventListener('mouseover', function (event) {
var currentElement = event.target;
// console.log(event.target);
if (currentElement.tagName === 'IMG') {
// console.log(currentElement.outerHTML + "is a photo");
imageInfo.source = currentElement.src;
// console.log("src is :" + imageInfo.source)
return imageInfo.source;
}
})
})();
See CodePen:
How to find the src URL for a photo by Trevor Rapp on
CodePen
This is how I thought about solving the problem in the most basic steps:
get the function to fire.
get the function to add an event listener that will perform an action on a mouseover event.
make that action know what the mouse is currently over.
figure out if what the mouse is currently over is an image or not.
create logic that will respond if it is.
that action that logic should do is return the source URL.
I will need to store that source URL if I am going to have to return it.
Here are how each of those solutions looked:
get the function to fire.
An IFFE is a great way to get a function to fire without having to worry about polluting the name space.
//skeleton for an IFFE statement
(function() {
})();
get the function to add an event listener that will perform an action on a mouseover event.
An event listener that could fire anywhere would have to be attached to the window or the document.
make that action know what the mouse is currently over.
This part will be combined with part 2. Event listener's first parameter is what type of event you want to listen for -- in this case 'mouseover. So now our code looks like this
(function () {
window.addEventListener('mouseover', function (event) {
//do stuff here
}
})()
figure out if what the mouse is currently over is an image or not.
*To figure out which element the mouse if currently over you would use Event.target.
The MDN definition for that is: *
The target property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event. --Event.Target
*So the code would then look like this: *
(function () {
window.addEventListener('mouseover', function (event) {
//get the current element the mouse is over
var currentElement = event.target;
}
})()
create logic that will respond if it is.
This was a little trickier since a photo or IMG can be presented in various ways.
I chose to create a solution for the simplest way, which is assuming that the web developer used the more syntactically correct version of an tag. However, there are many times when they may choose to apply a 'background-image' CSS property to a normal . Other things to consider could be the use of iframes, which can make detecting the attributes of child elements very frustrating since they don't allow bubbling to occur. To tell if an element is an , you can simply use elem.tagName === "IMG" for your logic check. While not included in the above code, if you wanted to check if a div is using the 'background-image', you could use something like element.getAttribute('style').includes('term') and switch out 'term' for something like 'url' or 'jpg' or 'png.' Kind of clunky and hacky, but just a thought. Anyway, the code would then become
(function () {
window.addEventListener('mouseover', function (event) {
//get the current element the mouse is over
var currentElement = event.target;
if (currentElement.tagName === 'IMG') {
//do stuff
}
}
})()
that action that logic should do is return the source URL.
Once you get the logic done and you have properly selected the element, then you can use element.src to get the source URL.
I will need to store that source URL if I am going to have to return it.
You can do this anyway you want, but I played around with instantiating an object since it sounded like the value would need to change often, but you didn't necessarily need to store previous values.
And so the final product could be something like this
(function() {
const imageInfo = new Object();
imageInfo.source = '';
window.addEventListener('mouseover', function (event) {
var currentElement = event.target;
// console.log(event.target);
if (currentElement.tagName === 'IMG') {
// console.log(currentElement.outerHTML + "is a photo");
imageInfo.source = currentElement.src;
// console.log("src is :" + imageInfo.source)
return imageInfo.source;
}
})
})();

Is it possible to bind to events on a child window from a parent?

Is it possible to bind functions to events on child windows?
document.getElementById('foo').onclick = function() {
var newWindow= window.open('other.html', "_blank");
newWindow.document.addEventListener("onreadystatechange", function(){
console.log('foo'); // This is never run. Can I construct the new window so that it is run "onreadystatechange"?
});
return false;
};
Note that I would like to bind an event to onreadystatechange. I wish to avoid a race condition, can I create a window, bind the events and then load the URL to avoid the race condition?
.addEventListener("onreadystatechange", ...)
Event properties start with "on". The event names on the other hand do not. I.e. it should be
.addEventListener("readystatechange", ...)
I have not tried avoiding the race condition because I know of no way to do so.
Ok, I'm not entirely sure how events and auxiliary browsing context initialization work with window.open(), the spec is quite complex there.
I'd just try setting DOM event breakpoints (chrome debugger has those) and see which events are fired in which order and then check if that works in other browsers.
That said, I think the simplest option here might to read the document.readyState property. If it's "complete" then the site is already fully loaded and no further state change event will be fired and you can execute your script directly instead of waiting for the event.
If you do this should be good to go.
var newwindow = window.open('other.html', "_blank");
var $ = newwindow.$; // add if needed
$(newwindow).bind('someEvent', function() { FunctionThatDoesSomethingInTheNewWindow });
return false;

inline javascript onclick event

This is my html code
Hit
This is my javascript file
function clickHandler(evt) {
var thisLink = (evt)?evt.target:Window.event.srcElement;
alert(thisLink.innerHTML);
return false;
}
But when i click the Hit Link, it redirects.
you need to pass in the event if you wish to preventDefault.
html:
Hit
script:
function runFunction (evt) {
evt.preventDefault();
evt.stopPropagation();
}
To tie both of the very-correct answers together, what's happened is you've inlined a function where you've written onclick="return runFunction();"
If you look at that, what it's really doing is going like this:
var link = document.getElementById("myLink");
link.onclick = function () { runFunction(); };
See the problem?
My runFunction is being called without any event object passed in, at all.
...which means that var thisLink = (evt) ? is going to return false, which means that it's going to try to run in oldIE-mode.
By writing onclick="runFunction", that's the same as saying:
link.onclick = runFunction;
Which means that when the onclick event happens, runFunction will be called, and in W3C-compliant browsers, it will be sent an event object.
Which is why that solution works.
The best way to avoid a lot of this confusion is to deal with JavaScript from inside of JavaScript, and to deal with HTML inside of HTML, so that you don't have to worry about how strings translate into code.
Now, to get all of this to work, AND prevent redirection, you want to do this:
for W3C browsers (the ones that pass the event parameter):
function runFunction (evt) {
// stops the default-action from happening
// means you need to find another way to fire it, if you want to later
evt.preventDefault();
// stops higher-up elements from hearing about the event
// like if you stop a submit button from "clicking", that doesn't stop the form
// from submitting
evt.stopPropagation();
//the oldIE versions of both of these are
event.cancelBubble = true;
event.returnValue = false;
}
When I plugged your code into chrome, I got this as the error in the console:
Uncaught TypeError: Cannot read property 'srcElement' of undefined
IF the javascript bombs out while processing, it never gets a chance to return at all so the browser tends to disregard what is in the onclick handler after the exception.
Since it bombed out... default behavior of anchor tags, which is to send you off to wherever the href says to go.
Try wrapping the contents of the function in a try/catch block and see what turns up if this kind of thing plagues you.

JavaScript event handlers -why no alert?

I'm a newbie at JavaScript trying to learn event handlers. Looking at this fiddle http://jsfiddle.net/mjmitche/uV4kv/ can anyone tell me why the pop up is not appearing when the link is clicked?
I've also copied the code below
click me
function addEventHandler(oNode, sEvt, fFunc, bCaptures){
if (typeof(window.event) != "undefined")
oNode.attachEvent("on"+sEvt, fFunc);
else
oNode.addEventListener(sEvt,fFunc,bCaptures);
}
function onLinkClicked(e) {
alert("you clicked the link");
}
function setUpClickHandler(){
addEventHanlder(document.getElementById('clickLink'), "click", onLinkClicked, false);
}
addEventHandler(window,"load",setUpClickHandler,false);
There are basically three problems:
You have some typos, e.g. "Hanlder" instead of "Handler" and "Sevt" instead of "sEvt".
The code is already run after page load, so the event handler you add to window will never be called. Change in jsFiddle from onLoad to no wrap (head).
You "IE detection" does not work. I get this error in Chrome:
Uncaught TypeError: Object http://fiddle.jshell.net/_display/# has no method 'attachEvent'.
Better would be to test whether the function window.attachEvent exists. I also think that window.event is only available when an event is raised.
If this is corrected, your code will run (DEMO).
Further notes:
Testing which method is supported (i.e. attachEvent or addEventListener) on every call of your function is unnecessary. It won't change during the life of the page. Better is to test only once at the beginning. Example:
var addEventHandler = (function() {
if(window.attachEvent) {
return function(oNode, sEvt, fFunc) {
oNode.attachEvent("on"+sEvt, fFunc);
};
}
else {
return function(oNode, sEvt, fFunc, bCaptures) {
oNode.addEventListener(sEvt,fFunc,bCaptures);
};
}
}());
This assigns a function the supported function to addEventHandler.
A couple of problems:
You have a recurring typo, "Hanlder" instead of "Handler". There are at least two, one where you do your setUpClickHanlder (sic) function, and one within it (addEventHanlder).
Also, you have "Sevt" where you mean "sEvt". (JavaScript is case sensitive.)
Let tools help you. Use a browser that gives you a console showing errors. Use a debugger for single-stepping through code, looking at variable values at runtime with inspectors, etc.
Your addEventHandler needs adustment:
function addEventHandler(oNode, sEvt, fFunc, bCaptures) {
oNode.attachEvent ? oNode.attachEvent ("on" + sEvt, fFunc) :
oNode.addEventListener (sEvt, fFunc, bCaptures);
}
It is in event handlers themselves that you need to check for window.event

Javascript event firing before action occurs

I am trying to write a script so that when I play an embedded sound object, a picture that I also have embedded will change.
function changePic() {
document.getElementById("sound").onclick = transform(document.getElementById("pic"));
}
function transform (pic) {
pic.src = "";
alert ("done");
}
The problem is that when I load the page, the Javascript code automatically runs even though I don't click play (autostart is set to false) on the sound object. Does anyone have an idea as to what is causing this?
When you write onclick = transform(...), you're calling transform and assigning the result to onclick.
You need to set the handler to an anonymous function that calls transform, like this:
document.getElementById("sound").onclick = function() {
transform(document.getElementById("pic"));
};
However, this is the wrong way to add events.
You should call element.addEventListener / element.attachEvent. (or just use jQuery)

Categories

Resources