Popunder run automatically - javascript

I have a code that inserts a popunder into all the links on my page.
However, I need something that makes this popunder / tabunder run automatically, regardless of the click.
I've tried in many ways but I can't.
Can someone help me?
window.onload = function() {
var puURL = 'http://google.com';
var puTS = Math.round(+new Date()/1000);
console.log('T.'+localStorage.puTS+'/'+puTS);
if (typeof localStorage.puTS == 'undefined' || parseInt(localStorage.puTS) <= (puTS - 3600)) {
var links = document.getElementsByTagName('a');
for(var i = 0, len = links.length; i < len; i++) {
links[i].onclick = function (e) {
var puHref = this.getAttribute("href");
var puTarget = this.getAttribute("target");
if (puHref !== '#' && puHref !== 'javascript:void(0)') {
e.preventDefault();
if (puTarget == '_blank') {
window.open(window.location.href);
}
window.open(puHref);
window.location.href = puURL;
localStorage.puTS = puTS;
}
}
}
}
};

I have placed your script locally under the HEAD Tag section and the function is triggered when I open the HTML file. I assume that the issue lays in the script placement.
If your script is stored outside the project (is external), make sure that you navigate to the correct root and double-check for spelling. Here is an example:
index.html
<!DOCTYPE html>
<html>
<head>
<script src="project/javascript_folder/myscript.js"></script>
</head>
<body>
...
</body>
</html>
You can check out W3Schools File Paths for more detail.
If you open your browsers DEV-TOOLS (by pressing the Right-Click button on your mouse while you hover over the page) and navigate to the console section, you should see the successful output from your function:
In my case, it is T.undefined/... where "..." represents a randomly generated number in the length of 10.

Related

Trying to replace every href on the document

i'm completely new to Javascript and I wanted to create an Greasemonkey Script that replaced "/text/othertext/" to "/text2/text3" on all the href elements of the document. That's what i came up with, and as expected, it doesn't work:
var links = document.getElementsByTagName('a');
for (i=0; i<links.length; i++)
{
var gethref = links[i].getAttribute('href');
gethref = gethref.replace(/text\/othertext/g,'text2\/text3');
links[i].setAttribute("href", gethref);
}
Thanks in advance!
Edit: ok, i know why my script is not working, but i don't know if it can be fixed, i'm trying to replace elements that load after the page is completely loaded (maybe with ajax?)
http://i.imgur.com/7n5V7Bi.png
This code works. Your code looks okay too. Perhaps you are loading the script before the document elements? Note how my elements are listed before my script:
link
link
<script>
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
var href = links[i].getAttribute('href');
href = href.replace('before', '#');
links[i].setAttribute('href', href);
}
</script>
Edit, based on your comments a dirty fix to cause delay in your app before running a script is to use the setTimeout function. To delay five seconds for example, you might use it like this:
link
link
<script>
setTimeout(function() {
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
var href = links[i].getAttribute('href');
href = href.replace('before', '#');
links[i].setAttribute('href', href);
}
}, 5000); // < --- note the time in ms here
</script>
Not too sure why your code wouldn't be working.
I've put together the following snippet which might help.
(function() {
var anchors = document.querySelectorAll('a');
for(var i = 0; i < anchors.length; i++) {
var newHref = anchors[i].getAttribute('href').replace(/text\/othertext/g,'text2\/text3');
anchors[i].setAttribute('href', newHref);
}
}());
a {
display: block;
}
<!DOCTYPE html>
<head></head>
<body>
Some link
Some other link
</body>
If you run this snippet you'll see only one anchor is updated correctly as intended.
Hope that helps you out!
The easiest solution would be to wrap your code in this:
window.onload = function(){
/* your code here */
};
This will ensure that your code (especially if you've placed your script in the of the document, won't load until the whole page is loaded (including text, images, etc).
window.onload = function() {
document.body.innerHTML = document.body.innerHTML
.replace('<a href="text/othertext/"', '<a href="text2/text3"');
};
<!DOCTYPE html>
<head></head>
<body>
Some link
Some other link
</body>

codemirror - detect and create links inside editor

I am using codemirror, configured to display javascript.
I have code like this:
...
var ref = 'http://www.example.com/test.html';
var ref2 = 'http://www.example.com/test2.html';
...
When displaying the editor it would be great if I could click on the links that might be present in the editor. The link would open the page on a different tab obviously.
is there an easy way to achieve this ?
Not really easy, but what you'd do is:
Write an overlay mode that recognizes such links. Basically, this is a mode that spits out a custom token type when it finds something that looks like a link, and null otherwise. You can use the simple mode addon to make this easier. You can use this token type's CSS class (for example "link" becomes cm-link) to style your links.
Make your editor use your overlay by calling the addOverlay method.
Register a mousedown event handler on your editor (instance.getWrapperElement().addEventListener(...)).
In this handler, check whether the event's target has the link CSS class. If it does, the user is clicking a link.
If so, use the coordsChar method, using the coordinates from your mouse event, to find the position in the document that was clicked. Extract the actual link from the document text around that position, and follow it.
(Or, even better, instead of directly interfering with the click, which might be intended to put the cursor in the link or select it, show a widget containing a regular link whenever the cursor is inside of link text.)
Here is a solution I came up with:
demo here: plunkr
code:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.17.0/codemirror.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.17.0/codemirror.css"/>
<style>
html, body { height:100%; }
.CodeMirror .cm-url { color: blue; }
</style>
</head>
<body>
<script>
var cm = CodeMirror(document.body);
cm.setValue('hover over the links below\nlink1 https://plnkr.co/edit/5m31E14HUEhSXrXtOkNJ some text\nlink2 google.com\n');
hyperlinkOverlay(cm);
function hoverWidgetOnOverlay(cm, overlayClass, widget) {
cm.addWidget({line:0, ch:0}, widget, true);
widget.style.position = 'fixed';
widget.style.zIndex=100000;
widget.style.top=widget.style.left='-1000px'; // hide it
widget.dataset.token=null;
cm.getWrapperElement().addEventListener('mousemove', e => {
let onToken=e.target.classList.contains("cm-"+overlayClass), onWidget=(e.target===widget || widget.contains(e.target));
if (onToken && e.target.innerText!==widget.dataset.token) { // entered token, show widget
var rect = e.target.getBoundingClientRect();
widget.style.left=rect.left+'px';
widget.style.top=rect.bottom+'px';
//let charCoords=cm.charCoords(cm.coordsChar({ left: e.pageX, top:e.pageY }));
//widget.style.left=(e.pageX-5)+'px';
//widget.style.top=(cm.charCoords(cm.coordsChar({ left: e.pageX, top:e.pageY })).bottom-1)+'px';
widget.dataset.token=e.target.innerText;
if (typeof widget.onShown==='function') widget.onShown();
} else if ((e.target===widget || widget.contains(e.target))) { // entered widget, call widget.onEntered
if (widget.dataset.entered==='true' && typeof widget.onEntered==='function') widget.onEntered();
widget.dataset.entered='true';
} else if (!onToken && widget.style.left!=='-1000px') { // we stepped outside
widget.style.top=widget.style.left='-1000px'; // hide it
delete widget.dataset.token;
widget.dataset.entered='false';
if (typeof widget.onHidden==='function') widget.onHidden();
}
return true;
});
}
function hyperlinkOverlay(cm) {
if (!cm) return;
const rx_word = "\" "; // Define what separates a word
function isUrl(s) {
if (!isUrl.rx_url) {
// taken from https://gist.github.com/dperini/729294
isUrl.rx_url=/^(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
// valid prefixes
isUrl.prefixes=['http:\/\/', 'https:\/\/', 'ftp:\/\/', 'www.'];
// taken from https://w3techs.com/technologies/overview/top_level_domain/all
isUrl.domains=['com','ru','net','org','de','jp','uk','br','pl','in','it','fr','au','info','nl','ir','cn','es','cz','kr','ua','ca','eu','biz','za','gr','co','ro','se','tw','mx','vn','tr','ch','hu','at','be','dk','tv','me','ar','no','us','sk','xyz','fi','id','cl','by','nz','il','ie','pt','kz','io','my','lt','hk','cc','sg','edu','pk','su','bg','th','top','lv','hr','pe','club','rs','ae','az','si','ph','pro','ng','tk','ee','asia','mobi'];
}
if (!isUrl.rx_url.test(s)) return false;
for (let i=0; i<isUrl.prefixes.length; i++) if (s.startsWith(isUrl.prefixes[i])) return true;
for (let i=0; i<isUrl.domains.length; i++) if (s.endsWith('.'+isUrl.domains[i]) || s.includes('.'+isUrl.domains[i]+'\/') ||s.includes('.'+isUrl.domains[i]+'?')) return true;
return false;
}
cm.addOverlay({
token: function(stream) {
let ch = stream.peek();
let word = "";
if (rx_word.includes(ch) || ch==='\uE000' || ch==='\uE001') {
stream.next();
return null;
}
while ((ch = stream.peek()) && !rx_word.includes(ch)) {
word += ch;
stream.next();
}
if (isUrl(word)) return "url"; // CSS class: cm-url
}},
{ opaque : true } // opaque will remove any spelling overlay etc
);
let widget=document.createElement('button');
widget.innerHTML='→'
widget.onclick=function(e) {
if (!widget.dataset.token) return;
let link=widget.dataset.token;
if (!(new RegExp('^(?:(?:https?|ftp):\/\/)', 'i')).test(link)) link="http:\/\/"+link;
window.open(link, '_blank');
return true;
};
hoverWidgetOnOverlay(cm, 'url', widget);
}
</script>
</body>
</html>
Here is a starting point, but it need to be improved.
LIVE DEMO
function makeHyperLink(innerTextInside)
{
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
if(all[i].innerText == innerTextInside)
{
all[i].innerHTML="<a target='_blank' href='https://google.com'>THIS IS A LINK TO GOOGLE</a>"
}
}
}

Stop javascript redirection on href="javascript:void"

I've been using a script which prefixes redirect.php on "onmouseevent" triggers. But I don't want it on certain sites, like google etc. Please see the code below:
var matchavailable = 0;
var disallowinks = "google,microsoft,yahoo";
$n("a").mousedown(function () {
var linkArray = disallowlinks.split(',');
for (var i = 0; i < linkArray.length; i++) {
if ($n(this).attr('href').indexOf(linkArray[i]) > 0) {
matchavailable = 1;
break;
}
else {
matchavailable = 0;
}
}
if (matchavailable == 0) {
if ($n(this).hasClass('linked')) {
}
else
{
$n(this).attr('href', "http://yoursite.com/redirect.php?q=" + encodeURIComponent($n(this).attr('href')));
$n(this).attr('target', '_blank');
$n(this).addClass("linked");
}
}
});
The javascript runs so far so good on all anchor tags. Just that, I have a popup which I show on my website and when I try to close the popup (X marks the spot), the redirect.php gets prefixed on that as well.
So my question is, how do we disallow the script to NOT run on anchor tags with the value starting with "javascript" ?
For example, i don't want it to run on:
<a href="javascript:void"> or <a href="any random parameter">
How do I go about this? WOuld be great to get some help

Modify UI of Log4Javascript

I have log4javascript setup so that it displays a log as follows:
However, I would like to get rid off some stuff, and instead would like the UI to be as below:
How can this be done? I am using the InPageAppender
Not easily, I'm afraid. log4javascript doesn't provide any options to do this and the log4javascript console is embedded in an iframe making customization of the CSS difficult. I'll add a configuration option for this in log4javascript 2.0.
You could create your own simplified appender but that would require a little work. A simpler alternative is to remove the UI you don't want using the appender's load event:
var appender = new log4javascript.InPageAppender();
appender.addEventListener("load", function() {
// Find appender's iframe element
var iframes = document.getElementsByTagName("iframe");
for (var i = 0, len = iframes.length; i < len; ++i) {
if (iframes[i].id.indexOf("_InPageAppender_") > -1) {
var iframeDoc = iframes[i].contentDocument || iframes[i].contentWindow.document;
iframeDoc.getElementById("switchesContainer").style.display = "none";
iframeDoc.getElementById("commandLine").style.display = "none";
}
}
});
I'm not sure if there's a config option, but this jsfiddle might get you started:
HTML
There's a delayed log.debug here to check that hiding of the toolbars doesn't break the logging.
<script src="http://log4javascript.org/js/log4javascript.js"></script>
<script type="text/javascript">
var log = log4javascript.getLogger("main");
var appender = new log4javascript.InPageAppender();
log.addAppender(appender);
log.debug("This is a debugging message from the log4javascript in-page page");
setTimeout(function() {
log.debug("This is a debugging message from the log4javascript in-page page");
}, 2000);
</script>
JS
This code waits until the log4javascript load event has fired, and then hides the toolbars.
function removeSwitchesContainers() {
var iframes = document.querySelectorAll("iframe");
iframes = Array.prototype.slice.call(iframes);
iframes.filter(function (iframe) {
return iframe.id && iframe.id.match(/log4javascript_\d+_\d+_InPageAppender_\d+/);
});
if (iframes.length < 1) {
return;
}
var iframe = iframes[0];
var sc = iframe.contentWindow.document.querySelectorAll("#switchesContainer");
sc = Array.prototype.slice.call(sc);
sc.forEach(function (switchesContainer) {
switchesContainer.style.display = "none";
});
}
log4javascript.addEventListener("load", removeSwitchesContainers);

autoclick link with javascript without id/class

got this example:
<html>
<head>
<script type="text/javascript">
function init(){
var linkPage = document.getElementById('linkid').href;
window.location.href = linkPage;
}
onload=init;
</script>
</head>
<body>
GO HERE
</body>
</html>
this script clicks the link "GO HERE". (works perfect)
but in my example i got no class or id in the link.
LINK NAME
is only thing that never change is the name of the link ("LINK NAME")
is it possible to search for "LINK NAME" and then click it like the working script above?
or something that will do what i need :D
JS has no way to search for a node by text contents (that I know of).
Array.prototype.forEach.call(document.getElementsByTagName('a'), function (elem) {
if (elem.innerHTML.indexOf('LINK NAME') > -1) {
window.location = elem.href;
}
});
Iterate over the links in the document and check the text:
for(var i = 0, len = document.links.length; i < len; i += 1) {
if(document.links[i].textContent === "LINK TEXT") {
document.links[i].click();
}
}
I'd just use the following bit, which uses jquery selection.
var link = $("a:contains('LINK TEXT')"); //get the a
var click = document.createEvent("Event"); //create event
click.initEvent("click", true, true);
link.dispatchEvent(click); // make it happen

Categories

Resources