Javascript not executing when right clicked into new tab - javascript

Here is my simple code
function goto() {
/* Some code to be executed */
if (a == "1")
location.href = "http://www.google.com";
else
location.href = "http://www.example.com";
}
And here is html
Hello
this works perfectly fine when i click normally but if i right click it and open in a new tab it doesn't execute.

try this:
Hello
function goto() {
/* Some code to be executed */
window.open("http://www.google.com");
}
if you want to open in new tab on mouse right click,
Hello
hit mouse right click and open in new tab
OR
u can try this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
function goto() {
window.location = "http://www.google.com";
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementsByTagName('a')[0].addEventListener('contextmenu', function (ev) {
ev.stopPropagation();
ev.preventDefault();
goto();
});
document.getElementsByTagName('a')[0].addEventListener('click', function (ev) {
goto();
});
}, false)
</script>
</head>
<body>
Hello
</body>
</html>

Try something like this:
Hello
<script>
document.getElementById('myId').addEventListener('contextmenu', function(ev){
gotoFunc(ev);
});
function gotoFunc(ev){
//run this when right clicked over #myId element
}
</script>

do it like this:
function changeDest(elem) {
/* Some code to be executed */
if (a == "1")
elem.href = "http://www.google.com";
else
elem.href = "http://www.example.com";
}
Hello

you can instead use Hello
This should do the trick. i.e adding the url to the href of the anchor tag

Related

break a href link event

I search a method to break the process after click a html a element. It is possible to make a onclick="alert();" event on this a element and the process is temporary stopped, till the OK button is clicked, or the process is breaked, when the page are reloaded or click previous page. Also the break is, but not perfect. With a confirm() it is similare, but by clicking "Cancel" the process is not canceled.
function myFunction() {
var confirmresult = confirm("Press a button!");
if (confirmresult === true) {
// OK = go away!
} else {
// Cancel = stay here!
}
}
<!DOCTYPE html>
<html>
<body>
example.com
</body>
</html>
The example don't work by me. Here the code:
<!DOCTYPE html>
<html>
<body>
example.com
<script>
function myFunction() {
var confirmresult = confirm("Press a button!");
if (confirmresult === true) {
// OK = go away!
} else {
// Cancel = stay here!
}
}
</script>
</body>
</html>
I have found a solution, but im not secure is it valide. Pleas help!
There is not so easy why the people think.
The thing is, it should be a solution for existing websites. No new coding is needed. Only insert the function myFunction(). onclick="myFunction()" is always present. And its only possible to put JS code in the head (not in the footer), because for this a custom <script> is always loaded via PHP in the webpages.
First, a methode with only code a new function with javascript:void(0);
The running code snippet function here don't work by me. Below a JSFiddle.
function myFunction() {
var confirmresult = confirm("Press a button!");
if (confirmresult === true) {
// OK = go away!
} else {
// Cancel = stay here!
document.getElementById("demo").removeAttribute("target");
document.getElementById("demo").href = "javascript:void(0);";
}
}
<!DOCTYPE html>
<html>
<body>
<a id="demo" href="https://www.example.com" onclick="myFunction()" target="_blank" rel="nofollow">example.com</a>
</body>
</html>
The code:
<!DOCTYPE html>
<html>
<body>
<a id="demo" href="https://www.example.com" onclick="myFunction()" target="_blank" rel="nofollow">example.com</a>
<script>
function myFunction() {
var confirmresult = confirm("Press a button!");
if (confirmresult === true) {
// OK = go away!
} else {
// Cancel = stay here!
document.getElementById("demo").removeAttribute("target");
document.getElementById("demo").href = "javascript:void(0);";
}
}
</script>
</body>
</html>
JSFiddle: https://jsfiddle.net/dLp8qtcm/
Second, a solution with preventDefault(). Consider the event instead a this. For this a edit of the webpages is needed for inside the event in onclick="myFunction(event)".
Thanks for the hints with the preventDefault(), but the examples in the answers don't work by me. Here is a working solution.
The running code snippet function here don't work by me. Below a JSFiddle.
function myFunction(e) {
var confirmresult = confirm("Press a button!");
if (confirmresult == true) {
// OK = go away!
} else {
// Cancel = stay here!
e.preventDefault();
}
};
example.com
example.com
<script>
function myFunction(e) {
var confirmresult = confirm("Press a button!");
if (confirmresult == true) {
// OK = go away!
} else {
// Cancel = stay here!
e.preventDefault();
}
};
</script>
JSFiddle: https://jsfiddle.net/osanthdq/
EDIT: The matter is a little bit complex. I have explained it here: Event keyword in js

window.onload Not Triggering in Injected Javascript?

I have a chrome extension that injects javascript code into a webpage like so
if (document.readyState === "complete") {
const html = `
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script type="text/javascript">
console.log(location.href);
function doStuff() {
console.log("do stuff");
}
console.log("onload");
window.onload = function () {
console.log("WINDOW LOADED");
doStuff();
}
</script>
</body>
</html>
`;
document.write(html);
}
However, after I navigate to the page and the extension injects the javascript, I can see in the console that it does log location.href and onload, but the window.onload does not trigger, and I do not see WINDOW LOADED in the console, nor is doStuff() called.
I have also tried using
window.addEventListener('load', (event) => {
console.log('page is fully loaded');
});
as well as
document.addEventListener('DOMContentLoaded', doStuff);
to no avail.
Any help would be appreciated, I have not been able to find anything that works.
I managed to fix this by including at the top of my <script>
setTimeout(() => {
let evt = document.createEvent('Event');
evt.initEvent('load', false, false);
window.dispatchEvent(evt);
}, 300);
And this now causes window.onload to trigger. hope this helps anyone with the same issue

Button onclick delete another browser window

I have two web pages.
First.html:
<script> window.onload = function(){ setTimeout(loadAfterTime, 3000) }; function loadAfterTime() { my_window = window.open("Second.html", "","status=1,width=100%,height=100%");}
this.window = previous_window ;
</script>
Second.html:
<html>
<head>
<script>
function closepopup()
   {
      if(false == previous_window.closed)
      {
         previous_window.close ();
      }
      else
      {
         alert('Window already closed!');
      }
   }
</script>
</head>
<body>
<button onclick="closepopup();">
Close
</button>
</body>
</html>
If we load first.html in a browser, after 3 seconds of load, the JavaScript will make a browser window with the URL set into Second.html.
I have added a button in the second.html file.
If we press that button, I want to delete/remove the previous browser window (first.html).
The window.open is working button window.close is not.
Please help.
Also, the code should perfectly work on mobile devices(Latest Chrome app on Android and IOS).
Any help will be appreciated.
First.html
<script>
window.onload = setTimeout(loadAfterTime, 3000);
function loadAfterTime()
{
window.open("Second.html","","status=1,width=100%,height=100%");
}
</script>
Second.html
<html>
<head>
<script>
function closepopup()
{
if(window.opener)
{
window.opener.close();
}
else
{
alert("Window already closed!");
}
}
</script>
</head>
<body>
<button onclick="closepopup();">Close</button>
</body>
</html>

Why doesn't IE8 handle iframe onload events?

Sample code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function on_iframe_load() {
document.getElementById('iframe_a').onload = function() {
alert('Thanks for the visit!');
};
}
</script>
</head>
<body>
<iframe name="iframe_a" id="iframe_a"></iframe>
Go!
</body>
</html>
It works in all major browsers with no problem, but IE8 (and probably prior versions) don't understand it.
Update: Just came up with a solution, but I'm not sure if it's right coding. Please review:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
var clicked = false;
function activate() {
clicked = true;
}
function pop() {
if (clicked) {
alert('Thanks for the visit!');
};
}
</script>
</head>
<body>
<iframe name="iframe_a" onload="pop();"></iframe>
Go!
</body>
</html>
Using inline attribute on iframe seems to fix this issue in IE8:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function onIframeLoad(iframe) {
if(iframe.src) {
alert('Thanks for the visit!');
}
}
function onLinkClick(url) {
document.getElementById('iframe_a').src = url;
}
</script>
</head>
<body>
<iframe id="iframe_a" onload="onIframeLoad(this);"></iframe>
Go!
</body>
</html>
update by request:
You should try writing more unobtrusive javascript. Writing code in such way may prevent you from such strange bugs in IE.
<!DOCTYPE html>
<html>
<body>
<iframe id="display-frame"></iframe>
Go!
<script>
window.onload = function() {
var iframe = document.getElementById('display-frame'),
link = document.getElementsByTagName('a')[0];
// load handler
function onIframeLoad() {
alert('Thanks for the visit!');
}
// event handlers
if(iframe.addEventListener) iframe.addEventListener('load', onIframeLoad, false);
else if(iframe.attachEvent) iframe.attachEvent('onload', onIframeLoad);
link.onclick = function() {
iframe.src = this.href;
return false;
}
};
</script>
</body>
</html>
It seems you can't add a load listener to an iFrame in IE using the DOM property once the page has loaded.
But you can use attachEvent, so:
function on_iframe_load() {
function foo() {
alert('Thanks for the visit!');
};
var el = document.getElementById('iframe_a');
if (el.attachEvent) {
el.attachEvent('onload',foo);
} else if (el.addEventListener) {
el.addEventListener('load', 'foo', false);
}
}
I was testing in IE 6 and reversed the usual test order so that attachEvent is used in preference to addEventListener. You may want to test more recent versions of IE to see if the opposite order works and also test other IE–like browsers such as Opera.
Edit
Modified the code after testing (silly me) to use addEventListener. Here's something that works in IE and others:
function on_iframe_load() {
function foo() {
alert('Thanks for the visit!');
};
var el = document.getElementById('iframe_a');
if (el.attachEvent) {
el.attachEvent('onload',foo);
} else {
el.onload = foo;
}
}
And if you use an onload attribute in the markup, you don't need to add the listener using script.
It works :)
tested on IE8, ff, chrome
var iframe = document.getElementById('iframeid');
if (iframe .attachEvent) {
iframe .attachEvent('onload',alert("IE Iframe loaded"));
} else {
iframe .onload = alert("Other than IE Iframe loaded");
}
Just use jquery:
$(iframe).bind( 'load', function(){} );

Opening a new tab on Google Chrome Extension

This is my background.html file, It works fine when opening in current tab but I want it to open in new tab, what am I doing wrong?
<html>
<head>
<script>
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
var action_url = "javascript:location.href='http://www.reddit.com/submit?url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title)";
chrome.tabs.create(tab.id, {url: action_url}, function(tab));
});
</script>
</head>
</html>
You should read the chrome.tabs.create documentation again. You are passing it invald parameters. You are also using location which is from the background.html document not the webpage document the code is expecting instead of the tab parameter passed to the chrome.browserAction.onClicked listener.
<html>
<head>
<script>
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
var action_url = "http://www.reddit.com/submit?url=" + encodeURIComponent(tab.href) + '&title=' + encodeURIComponent(tab.title);
chrome.tabs.create({ url: action_url });
});
</script>
</head>
</html>
You can try this
<html>
...
<body>
<script>
function createTab() {
chrome.tabs.create({url: "http://www.stackoverflow.com"});
}
</script>
Create a new tab
</body>
</html>
<html>
<head>
<script type="text/javascript">
window.master = ({
newtab: function(url, callback) {
callback = callback === true ? (function() { this.close(); }) : callback;
try {
chrome.tabs.create({
url: url
});
if(typeof callback === "function") { callback.call(this, url); }
} catch(e) {
/* Catch errors due to possible permission issues. */
}
},
link: function(event, close) {
event = event ? event : window.event;
event.preventDefault();
this.newtab(event.href, close);
},
close: function() { window.self.close(); }
});
</script>
</head>
<body>
<!-- Usage is simple:
HTML:
<a href="http://example.com/" onclick="master.link(event)" />
JavaScript:
master.newtab("http://example.com/", true);
-->
</body>
</html>
If you insist on using a popup and want it to close as soon as it is opened, then use what is above. Simply add the link string and a true boolean to the master.newtab function to have it open the new tab and then close the popup.
If you change your mind about closing the popup, you can replace the true boolean with a function to execute if the new tab was created without any errors. You can also use the master.link function for calling the master.newtab function from an anchor element.
The best thing about using Chrome Extensions is you never have to worry about support issues! :D

Categories