I have a large number of links I want to print. The links are in local HTML files, so I am able to add scripts to them. I attempted a few things, but I did not get to the end. The best I have so-far achieved is to open the links I want to print in separate tabs, and the Windows.print() function does not work. Could someone help me to what I might be missing here, or point me to how I might get to my goal. Please see the code below:
<!doctype html>
<html>
<head>
<title>Print</title>
<script>
function pickLinks() {
const anchors = document.getElementsByTagName("a");
for (const a of anchors) {
const url = a.href;
const urlBase = "https://www.huffpost.com/entry/";
if (url.startsWith(urlBase)) {
console.log(getQid(url));
openInNewTab(url);
}
}
}
function getQid(url) {
const res = url.split("-");
return res[res.length - 1];
}
function openInNewTab(url) {
const win = window.open(url, '_blank');
win.print();
//win.focus();
}
</script>
</head>
<body>
<h1>Print</h1>
<button onclick="pickLinks()">PRINT</button>
Link
Link
Link
Link
</body>
</html>
Ideally I would like the print to be a PDF with a filename that reflects the URL, such as getQid(url) in the code above.
Many thanks in advance!
Related
Hi I have this script that opens a new tab when clicking anywhere on the page but it works with only one link, I would like to make it so it can open links multiple times, consecutively. I would really appreciate any help.
<script type='text/javascript'>
var popup = function() {
window.open ("https://example.com/", "Window","status=1,toolbar=1,width=500,height=500,resizable=yes");
}
</script>
<body onclick='popup();'>
I tried multiples onclick in the body tag but it didn't work
If you want to cycle through multiple URLs, try this out.
<!DOCTYPE html>
<html>
<body onclick='popup();'>
<script>
const urls = ["https://www.google.com", "https://www.stackoverflow.com", "https://www.gmail.com"];
let counter = 0;
const popup = () => {
window.open(urls[counter++ % urls.length]);
}
</script>
</body>
</html>
First things first, I'm brand new to Javascript and Regex. I've only been dipping my toes in this past month. I've been trying to put together away to paste a url into a text input then automatically trim it down to just the host name and validate it before I'm able to push the button.
I've gotten it working a few different times but I keep running into the same issue: After a certain period of time, it simply stops working.
I've reformatted and cleaned up the code a few times (though, I'm sure it's still very sloppy because I'm new at this) and I can get it working again. But after an hour or so of working, it stops working. Reloading the page doesn't make a difference. Even restarting my computer doesn't make a difference. It simply stops working.
My only guess is that there must be something about the way I'm going about this which is causing it crash or stall out. Perhaps a formatting issue, perhaps the methodology altogether is flawed. I just don't know enough to be able to diagnose it yet.
Hopefully, some of you nice people would be able to point out my flaws or point me in the right direction of how to fix this. I've searched and I couldn't find anyone who was trying to do the things I'm doing all in one build (preparing to myself to be proved wrong here).
Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<input id="notesUrlInput" type="text" placeholder="URL Goes here" pattern="^(?!www\.)[a-zA-Z0-9\-]+\.[a-zA-Z0-9]+$" autocomplete="off">
<button id="notesExecuteButton" disabled>Execute</button>
<span id="notesUrlOutput"></span>
<!------------------------------------------------------------------------------->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
(function () {
var timeout = null;
var notesUrlOutput = document.getElementById("notesUrlOutput");
var notesExecuteButton = document.getElementById("notesExecuteButton");
document.getElementById('notesUrlInput').addEventListener('keyup',
function (e) {
clearTimeout(timeout);
timeout = setTimeout(
function () {
rawInput = $('#notesUrlInput').val();
cleanInput = rawInput.replace('www.', '');
cleanInput = cleanInput.replace('http://', '');
cleanInput = cleanInput.replace('https://', '');
cleanInput = cleanInput.replace(/\/.*/,'');
$('#notesUrlInput').val(cleanInput);
if (cleanInput.value == "") {
notesUrlOutput.innerHTML = "";
notesExecuteButton.disabled = true; return false;
} else if(!notesUrlInput.checkValidity()) {
notesUrlOutput.innerHTML = "Invalid URL: Please provide a valid URL";
notesExecuteButton.disabled = true; return false;
} else {
notesUrlOutput.innerHTML = "Input OK";
notesExecuteButton.disabled = false; return false;
}
}, 400);
});
})();
</script>
</body>
</html>
Frustratingly, when I pasted this code in here and ran it, it worked. As soon as I opened the file I copied this from in my browser. It stopped working. I just don't understand it.
From your code it looks like you want to extract just the domain name from the input field.
You mix JavaScript DOM calls and jQuery, which is fine. It is usually easier to interact with the DOM using just jQuery. Here is your code rewritten in jQuery:
const cleanRegex = /^https?:\/\/(?:www\.)?(.*)\/.*$/;
const validRegex = /^[\w\-]+(\.[\w]+)+$/;
(function () {
$('#notesExecuteButton').prop('disabled', true);
$('#notesUrlInput').on('input', function(event) {
let val = $(this).val();
let cleaned = val.replace(cleanRegex, '$1');
$(this).val(cleaned);
if(!cleaned) {
$('#notesUrlOutput').text('');
$('#notesExecuteButton').prop('disabled', true);
} else if(!cleaned.match(validRegex)) {
$('#notesUrlOutput').text('Invalid URL: Please provide a valid URL');
$('#notesExecuteButton').prop('disabled', true);
} else {
$('#notesUrlOutput').text('Input OK');
$('#notesExecuteButton').prop('disabled', false);
}
});
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input id="notesUrlInput" />
<button id="notesExecuteButton" style="disabled: disabled;">Go</button>
<div id="notesUrlOutput"></div>
Explanation:
.on('input') - fires every time something changes in the input field- val.replace(cleanRegex, '$1') - clean up: strip protocol and www prefix, and URL path (any text after domain
cleaned.match(validRegex) - check validity of domain
.prop('disabled', true/false) - add/remove disable property
I'm trying to open build a system which opens a new link every time an anchor tag is clicked. I tried using random function but at times it opens the same link again and again. But whereas as I want the link to open in an order and follow the cycle.. That is if I have three links, the user clicking the anchor text first time will open the first link, then second, then third and later again the first link..
This means the link must change if a different user clicks.
Here is a code that I found which uses random function..
<script type="text/javascript'>
function random_3(){
var myrandom=Math.round(Math.random()*2)
var link1="http://www.codingforums.com"
var link2="http://www.cssdrive.com"
var link3="http://www.dynamicdrive.com"
if (myrandom==0)
window.location=link1
else if (myrandom==1)
window.location=link2
else if (myrandom==2)
window.location=link3
}
</script>
<form>
<input type="button" value="random link!" onClick="random_3()">
</form>
so can someone help me out with this?
I tried using random function but at times it opens the same link again and again
You're probably getting the same link several times in succession due to the random calculation that you're using.
Try the following instead:
var myrandom=Math.floor(Math.random()*3);
You should get a better distribution this way.
Now, regarding your original question, if you want a persistent state to be kept between page reloads, so that each time the link is different, you'll probably need to use cookies or localStorage for storing what was the last used index for that user.
Example:
var links = ['http://www.codingforums.com', 'http://www.cssdrive.com', 'http://www.dynamicdrive.com'];
function nextLink() {
var index = localStorage.getItem('lastPos') || -1;
index = (index + 1) % links.length;
localStorage.setItem('lastPos', index);
return links[index];
}
What you need to do is save the index of the link, and then increase it every time so that you cycle through the links in order.
Here's a working example of what you want:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
urls = ['http://domain1.com','http://domain2.com', 'http://domain3.com', 'http://domain4.com'];
var urlIndex = 0;
function openUrl(){
url = urls[urlIndex % urls.length];
window.location = url;
urlIndex ++;
}
</script>
Get a link
</body>
</html>
Here's a demo :)
First of all, you have to list your links in an array. Second, you have to define a variable that hold the last opened link's index in that array, to void a successive opening of the same link (indeed it's a URL). In general you may follow something like the following code:
urls = ['http://domain1.com','http://domain2.com', 'http://domain3.com', 'http://domain4.com'];
var lastUrl = '';
function getRandomIndex(arr){
return Math.floor(Math.random() * ((arr.length+1) - 1));
}
function openUrl(){
url = urls[getRandomIndex(urls)];
do {
if (url == lastUrl){
url = urls[getRandomIndex(urls)];
}
else{
lastUrl = url;
//Using alert instead of window.location for testing
alert(url)
//window.location = url;
}
}
while (lastUrl != url);
}
Then for test:
Click here for test
This is an online Demo
Reference: Generating random whole numbers in JavaScript in a specific range?
Edit
According your comment, the requirement is pretty easier, instead of choosing according to random value, you will define lastUrl as an integer store and every time the openUrl() is called, it will be increased by 1 after checking its value if it is greater than urls array length or not as follows:
Modified openUrl
urls = ['http://domain1.com','http://domain2.com', 'http://domain3.com', 'http://domain4.com'];
//lastUrl Index in urls array
// Global variable
var lastUrl = 0;
function openUrl(){
if (lastUrl > (urls.length - 1)){
//reset it to 0
lastUrl = 0;
}
else{
url = urls[lastUrl];
lastUrl++;
alert(url)
//window.location = url;
}
}
var myrandom = 0;
function random_3(){
myrandom += 1;
var link1="http://www.codingforums.com";
var link2="http://www.cssdrive.com";
var link3="http://www.dynamicdrive.com";
if (myrandom==1)
window.open('http://www.codingforums.com','_blank');
else if (myrandom==2)
window.open('http://www.cssdrive.com','_blank');
else if (myrandom==3)
window.open('http://www.dynamicdrive.com','_blank');
else if (myrandom>3)
window.open('http://www.codingforums.com','_blank');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form>
<input type="button" value="random link!" onClick="random_3()">
</form>
You can count click like user click on button and basis on this manage.
I have this code to have random background images, I need to make sure that when someone clicks on the picture to open a web page, one for each image. Can you help me please?
this is the code:
</head><body onLoad="LoadRandomBackground(); StartBackgroundRefreshTimer()">
</body>
</head>
<body onLoad="LoadRandomBackground()">
</body>
<script type="text/javascript">
var bgImages = [];
bgImages[1]="/img/sfondi/bg-stanem.jpg";
bgImages[2]="/img/sfondi/booking.jpg";
function LoadRandomBackground()
{
var randomImageIndex = Math.floor(Math.random()*bgImages.length)
document.body.background = bgImages[randomImageIndex];
}
function StartBackgroundRefreshTimer()
{
var timer = setInterval('LoadRandomBackground()',1000); // millisecondi
}
</script>
thank's
can someone help me?
you could create a second array ...
var bgImagesUrls=[];
then assign the urls to the array using the same indexes for the bgImages
you could then place in LoadRandomBackground
document.<someelement>.href=bgImagesUrls[randomImageIndex];
Here a short possible script http://jsfiddle.net/d2Dmh/3/
bgImages[0]= {url: ...
here you can place the url you want as destination as another parameter (destination : "url")
And with
window.location = "http://www.google.com/";
you can navigate to the new page in the document click function.
You need jquery for my example.
I'm having some trouble trying to get a fairly simple popupper to work. The idea is that the parent should open a popup window and then append a div in it.
The relevant parts of the code:
parent.html:
var childWindow;
function togglePref() {
childWindow = window.open("popup.html", "prefPopup", "width=200,height=320");
}
function loadPopupElements() {
var prefElements = document.getElementById("prefBrd").cloneNode(true);
var childDoc = childWindow.document;
var childLink = document.createElement("link");
childLink.setAttribute("href", "pop.css");
childLink.setAttribute("rel", "stylesheet");
childLink.setAttribute("type", "text/css");
childDoc.head.appendChild(childLink);
childDoc.body.appendChild(prefElements);
}
popup.html:
<head>
</head>
<body onload="opener.loadPopupElements();">
</body>
This works fine with Safari and Chrome, but for some reason IE refuses to append anything.
Ok, I managed to work around the problem with a uglyish solution using innerHTML. Apparently, as Hemlock mentioned, IE doesn't support appending children from a another document. Some suggested to take a look at the importNode() method but I seemed to have no luck with it either.
So, the workaround goes as follows:
parent.html:
var childWindow;
function togglePref() {
childWindow = window.open("popup.html", "prefPopup", "width=200,height=320");
}
function loadPopupElements() {
var prefElements = document.getElementById("prefBrd");
var childDoc = childWindow.document;
childDoc.body.innerHTML = prefElements.innerHTML;
}
popup.html:
<head>
<link href="pop.css" rel="stylesheet" type="text/css">
</head>
<body onload="loadElements();">
</body>
<script type="text/javascript">
function loadElements() {
opener.loadPopupElements();
}
</script>
This seems quite a nasty way to go because in my case the #prefBrd contains some input elements with dynamically set values, so in order for the popup.html to grab them, it has to do a bit of iteration at the end of the loadElements() function, which wouldn't have been necessary using appendChild.