I'd like to have a button on a HTML page, when I click the button, a JavaScript function have to copy the current URL and write to an already existing TXT file, and overwrite it's current data.
I tried this code:
var button = document.getElementById("myButton");
// Attach a click event listener to the button
button.addEventListener("click", function() {
// Wait 0.2 seconds before executing the function
setTimeout(function() {
// Get the current URL
var currentURL = window.location.href;
// Open or create the text file and overwrite its current data
var file = new File([currentURL], "URLs.txt", {type: "text/plain", overwrite: true});
// Copy the contents of the file
file.select();
document.execCommand("copy");
}, 200);
});
Call the following function with the text file content:
function downloadTxtFile(content) {
var aElem = document.createElement("a");
aElem.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
aElem.setAttribute("download", "filename.txt");
aElem.style.display = "none";
document.body.appendChild(aElem);
aElem.click();
aElem.remove();
}
downloadTxtFile("https://google.com.br");
You can change the function to get the filename. In this form, it only gets the content of the file, which is the URL.
Related
We're trying to make a website in html that shows an alert if the value in a local text file changes to, for example, 1. And if the value changes to 0, we want the alert to not show. We have managed to read from the file, and using php made it show an alert. But we can't make it update without refreshing the page and also not closing the alert if the value changes.
We have javascript code that reads from our text file, and updates without refreshing the page, but right now it just prints the value from the file. We want it to show or hide a div depending on the value in the file.
window.onload = function() {
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
function loadFile() {
reader.open('get', 'value.txt', true);
reader.onload = displayContents;
reader.send(null);
}
function displayContents() {
if (reader.readyState == 4) {
var el = document.getElementById('main');
el.innerHTML += reader.responseText + "<br>";
outputData();
}
}
function outputData() {
var refresh = 2000;
update = setTimeout(loadFile, refresh);
}
loadFile()
}
I am using jQuery to open a PDF in a new window or tab. For the most part, it works. I can click the link, and the PDF opens in a new tab.
The problem occurs when I open another PDF.
The new PDF will open, along with the previous PDF. By the time I get to the 5th PDF, there will be 4 additional tabs from the PDFs that I previously opened.
I am working with datatables. I click a link that contains data-attributes, which then opens a modal. From inside the modal is where I'll have another click event that will then open the PDF:
$('#resultsTable').on('click', 'tr > td > a.uploadDocs', function(e)
{
e.preventDefault();
$('#editForm input, select').val(''); // <- clear previous values
var editbooking = $(this).attr('data-editbooking');
var editpartnercode = $(this).attr('data-editpartnercode');
// open PDF click event
// takes vars editbooking and editpartner to build path and filename
$('#downloadPDF').on('click', function()
{
var pdf = '../PartnerUploads/' + editpartnercode + '/' + editbooking + ".pdf";
$.get(pdf)
.done(function()
{
window.open(pdf);
}).fail(function(textStatus)
{
if(textStatus.status == 404)
{
return false;
}
});
// *** edit ***
$('#downloadPDF').off('click');
});
});
All of the above works as far as navigating to the directory, and then opening the file. But it should not open all of the files that were previously opened.
How can I find why additional tabs are being opened when opening a PDF?
As mentioned in comments, you have nested event binding.
Every time you will click on #resultsTable, you will create a new event for #downloadPDF every single time, resulting in exponentially growing the number of tabs you open.
Use $('#downloadPDF').off('click') after window.open(pdf); and one inside fail(function(textStatus).
Solution:
$('#resultsTable').on('click', 'tr > td > a.uploadDocs', function(e)
{
e.preventDefault();
$('#editForm input, select').val(''); // <- clear previous values
var editbooking = $(this).attr('data-editbooking');
var editpartnercode = $(this).attr('data-editpartnercode');
// open PDF click event
// takes vars editbooking and editpartner to build path and filename
$('#downloadPDF').on('click', function()
{
var pdf = '../PartnerUploads/' + editpartnercode + '/' + editbooking + ".pdf";
$.get(pdf)
.done(function()
{
window.open(pdf);
$('#downloadPDF').off('click');
}).fail(function(textStatus)
{
if(textStatus.status == 404)
{
return false;
}
$('#downloadPDF').off('click');
});
});
});
I have a code to export json data to Excel via javascript, it works fine in Chrome. However the same code doesn't work in IE where a click event is fired via code:
download = function (content, filename, contentType) {
if (!contentType) contentType = 'application/octet-stream';
var a = document.getElementById('idA');
var blob = new Blob([content], {
'type': contentType
});
a.href = window.URL.createObjectURL(blob);
a.download = filename;
var eid = '#' + id;
//$(eid)[0].click();
var l = document.getElementById('idL');
alert('1'); //this one works
l.click();
alert('2'); //this doesn't
};
download function is fired by clicking a button and clicking anchor href causes blob downloading in Excel. I need to make this work in IE.
I want to pass the input file from content page to extension background script, and then load it with FileReader() in the extension background script.
So in the web page I have a <input type="file"> and from onchange event I pass the file from content script to background page like this:
var myfile = document.getElementById('fileid').files[0];
chrome.runtime.sendMessage({myevent: "start", inputfile: myfile}, function(response) {});
in the background script I have this:
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.myevent==="start")
{
var reader = new FileReader();
reader.onload = function(e) {
// file is loaded
}
reader.readAsArrayBuffer(message.inputfile);
}
});
but FileReader not load it, I'm not sure if this is correct way , but all i need is to pass the input file element to background script and load it with FileReader to send it with HTTP POST from background script. Please tell me what is wrong or how to do it correctly. It will help a lot if I see a sample code, because I'm new to chrome extension development, and not so experienced.
All messages send through the Chrome extension messaging API MUST be JSON-serializable.
If you want to get the contents of a file at the background page, you'd better create a (temporary) URL for the File object, pass this URL to the background page and use XMLHttpRequest to grab its contents:
// Create URL
var url = URL.createObjectURL(myfile);
// Pass URL to background page (ommited for brevity) and load it..
var x = new XMLHttpRequest();
x.onload = function() {
var result = x.response;
// TODO: Use [object ArrayBuffer]
};
x.open('GET', url); // <-- blob:-url created in content script
x.responseType = 'arraybuffer';
x.send();
Though why do you want to send the file to the background page? Content scripts can also send cross-origin requests.
This works for chrome. You could find the whole production code here.
https://github.com/Leslie-Wong-H/BoostPic/tree/7513b3b8d67fc6f57718dc8b9ff1d5646ad03c75/BoostPic_Chrome/js
main.js:
// Crossbrowser support for URL
const URLObj = window.URL || webkitURL;
// Creates a DOMString containing a URL representing the object given in the parameter
// namely the original Blob
const blobUrl = URLObj.createObjectURL(imageBlob);
console.log(blobUrl);
chrome.runtime.sendMessage(blobUrl, (res) => {
imgUrl = res;
console.log(imgUrl);
clearInterval(refreshIntervalId);
// To prevent that it happens to halt at " Image uploading ..."
setTimeout(() => {
var imgUrlText = document.querySelector(imgUrlTextBoxId);
imgUrlText.value = imgUrl;
}, 1000);
// double check to clear interval to prevent infinite error loop of LoadingStateOne
// Hope it works.
setTimeout(() => {
clearInterval(refreshIntervalId);
}, 500);
console.log("Stop uploading state message");
background.js:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.startsWith("blob")) {
console.log("RECEIVED");
getBase64Url(request).then((res) => {
console.log("Arrived here");
// Acquired from https://stackoverflow.com/questions/18650168/convert-blob-to-base64/18650249#
const reader = new FileReader();
reader.readAsDataURL(res);
reader.onloadend = function () {
const base64data = reader.result;
console.log(base64data);
I have a textarea that can, quite obviously, be edited using keyboard entry. I also want to be able to load a file using an html input. I have done so, using the onchange event. (jsfiddle code linked below).
Suppose I load a file using the file loader - which works correctly in the example.
Then, I edit this file. Realising that the changes I have made are not desired, I want to reload this file. However, when using the html input, nothing changes since the selected file remains the same (the onchange event is not triggered). Is there a way to reload a file using an html input. (The only workaround I have found is to load a different file, then reload the original file ... which is not very elegant).
http://jsfiddle.net/aroberge/8PZyK/1/
var load_file = function() {
$("#fileInput").show();
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$("#editor").text(reader.result);
$("#fileInput").hide();
};
reader.readAsText(file);
});
};
$("#load").on("click", function(evt) {
load_file();
});
You could clear out the fileInput value after you've read the file from it:
updated fiddle:
http://jsfiddle.net/8PZyK/8/
var load_file = function() {
$("#fileInput").show();
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
if (fileInput.files && fileInput.files.length > 0) {
var file = fileInput.files[0];
var reader = new FileReader();
fileInput.value = "";
reader.onload = function(e) {
$("#editor").val(reader.result);
$("#fileInput").hide();
}
};
reader.readAsText(file);
});
};
$("#load").on("click", function(evt) {
load_file();
});
After the file input has changed, and you grab out the data, simple reset the input field like so:
fileInput.value = ""; // Or with jQuery, $('input[file]').val('')
This will trigger another change (which you'll want to ignore), but will allow the user to select the same file again and still give you a change event.