Angular: How to get copied URL from clipboard? - javascript

So this is how I extract the copied text from clipboard:
const data = event.clipboardData.getData('text/html');
But this code does not work if I copied a URL. The data will be "" empty. Not sure why is it different with a normal text.
How do I get the copied URL?
EDIT
The event I got is from paste event:
paste(event: ClipboardEvent) {
const data = event.clipboardData.getData('text/html');
}
From this HTML element (I am using Angular):
<div
id="content"
contentEditable="true"
(paste)="paste($event)"
></div>

Not sure what is the event in your code, but you can get data from clipboard anywhere in your browser via Clipboard API
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/readText
const copiedData = await navigator.clipboard.readText()

So from what I've read from this Codepen, the code takes the textContent from the quote blocks and then put them all in the clipboard
handleCopyClick.addEventListener('click', () => {
let text = quoteText.textContent;
let author = quoteAuthor.textContent;
navigator.clipboard.writeText(`${text} ${author}`);
});
Adapting to your case though, the code would look something like this:
paste(event: ClipboardEvent) {
let url = urlBlock.textContent;
navigator['clipboard'].writeText(`${url}`)
}
Props to this FreeCodeCamp article for the inspiration.
This one SO post might also answer some of your questions too.

Actually I found that the clipboardData sometimes hold different types of string. In my code:
const data = event.clipboardData.getData('text/html');
This only extract text/html type.
There are other types like text/plain. So this is my solution:
let data = event.clipboardData.getData('text/html');
data = data && data.length > 0 ? data : event.clipboardData.getData('text/plain');
If text/html is empty, then get text/plain data.

Related

How to pass URL query string to website header?

I have this type of URL:
www.domain.com/postname?emailid=somethingsomething
I must place this part:
somethingsomething
inside WP header, more accurate inside JS snippet, as follows:
<script>
window.HashedEmail = 'somethingsomething';
</script>
EDIT: Suggested answer shows how to extract particular data but not how to place extracted data into header, for example - how to manipulate with extracted dataset
Maybe I missed something but this looks like a solution for me
const urlSearchParams = new URLSearchParams(window.location.search);
const emailid = urlSearchParams.get('emailid');
window.HashedEmail = emailid;

How to get file extension from file content using Node.js

I need some help. I need to fetch what the file type should be from the file containing only using Node.js. I am explaining the scenario below.
Let's say I have some content like below.
let fileContent = "The textContent property sets or returns the text content of the specified node, and all its descendants."
As we can see here the variable fileContent has some text data and I want to write this data into one file. So for that, I need to create the file with a proper extension like abc.txt. Similarly, If fileContent has some json data then I will create the file like abc.json and write the value inside it.
So here I need to fetch what should be the type of file from this content only using Node.js. If anybody has a solution for this will be a great help.
You can use popular file-type package for this. You can send buffer/file/stream/blob as an input and get file type as an output.
const FileType = require('file-type');
...
const { ext, mime } = await FileType.fromBuffer(your_data);

Add Signature field to pdf in javascript

after hours of searching for a solution, I've decided to ask my first question on stackoverflow.
Our application uses pdf-lib (https://www.npmjs.com/package/pdf-lib) to modify existing PDFs, e.g. add images. We're now looking for a way to ad signature form fields to the PDF as well.
With pdf-lib, it is possible to add a bunch of form fields, except for signature fields. It is possible to get them (https://pdf-lib.js.org/docs/api/classes/pdfform#getsignature), but unlike other fields, there's no create method (e.g. https://pdf-lib.js.org/docs/api/classes/pdfform#createtextfield).
I've digged deeper in the code, and found access to the PDFForms AcroForm (https://pdf-lib.js.org/docs/api/classes/pdfform#acroform). It's possible to add fields with it, but I wasn't able to create the correct Field beforehand (in my opinion it has to be PDFSignature or PDFAcroSignature).
I found out that other fields like PDFAcroText have create methods
class PDFAcroText extends PDFAcroTerminal {
static fromDict = (dict: PDFDict, ref: PDFRef) => new PDFAcroText(dict, ref);
static create = (context: PDFContext) => {
const dict = context.obj({
FT: 'Tx',
Kids: [],
});
const ref = context.register(dict);
return new PDFAcroText(dict, ref);
};
Those get called by the wrapper functions (like createTextfield as mentioned):
createTextField(name: string): PDFTextField {
assertIs(name, 'name', ['string']);
const nameParts = splitFieldName(name);
const parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);
const text = PDFAcroText.create(this.doc.context);
text.setPartialName(nameParts.terminal);
addFieldToParent(parent, [text, text.ref], nameParts.terminal);
return PDFTextField.of(text, text.ref, this.doc);
}
I looked for other js libs that provide the possibility to add signature form fields, but I wasn't able to find the answer to this - except for pay to use libs like pdfjs.express.
Assuming that they are capable of adding such fields, there must be a way to do this!
Please let me know if anyone of you figured out how to do this or if there's another solution for this.
Thank you in advance!
Greetings
Alex
The Acrobat PRO itself doesn't have an option to put a straight "Signature" field. You may "request" a signature, but only using Adobe's services, and an email is required.
If you plan to add a signature by the code, take a look at their "Fill Form" example. They put an image on top of a Button field, but an Image field also works.
const signatureImageField2 = form.getButton('button-signature-field')
signatureImageField2.setImage(signatureImage)
const factionImageField = form.getField('image-signature-field_af_image')
factionImageField.setImage(signatureImage)

Gmail API - Parse message content (Base64 decoding?) with Javascript

I'm trying to use the Gmail API to get a user's email, grab the message subject and body, and then display it on a webpage. I'll be doing other stuff with it, but this is the part that I am having difficulty with. I am using Angular.js.
Here is my API call:
function makeApiCall() {
gapi.client.load('gmail', 'v1', function() {
var request = gapi.client.gmail.users.messages.list({
labelIds: ['INBOX']
});
request.execute(function(resp) {
var content = document.getElementById("message-list");
angular.forEach(resp, function(message) {
var email = gapi.client.gmail.users.messages.get({'id': message.id});
// var raw = email.payload.parts;
// console.log(raw);
content.innerHTML += JSON.stringify(email) + "<br>";
})
});
});
}
So gapi.client.gmail.users.messages.list returns an array of my messages, with their ID numbers. That is working.
The call to gapi.client.gmail.users.messages.get({<specific message ID>}) outputs this - {"B":{"method":"gmail.users.messages.get","rpcParams":{},"transport":{"name":"googleapis"}}}.
Not sure what that is, but trying to get the message payload (email.payload.parts), results in undefined. So, how can I get the message content?
Also, I would assume that if I can get the message contents, I would then have to Base64 decode the contents to get some English out of it. Any suggestions for that would be of great help also. I've found this: https://github.com/kvz/phpjs, but since I'm not sure how to go about getting the message contents so that I can try and decode them, so not sure if that php.js is of an help in that regard.
Regarding the Base64 decoding, you can use
atob(dataToDecode)
For Gmail, you'll also want to replace some characters:
atob( dataToDecode.replace(/-/g, '+').replace(/_/g, '/') );
The above function is available to you in JavaScript (see ref). I use it myself to decode the Gmail messages. No need to install extra stuff. As an interesting tangent, if you want to encode your message to Base64, use btoa.
Now, for accessing your message payload, you can write a function:
var extractField = function(json, fieldName) {
return json.payload.headers.filter(function(header) {
return header.name === fieldName;
})[0].value;
};
var date = extractField(response, "Date");
var subject = extractField(response, "Subject");
referenced from my previous SO Question and
var part = message.parts.filter(function(part) {
return part.mimeType == 'text/html';
});
var html = atob(part.body.data.replace(/-/g, '+').replace(/_/g, '/'));
Depending on what your emails look like (single text/plain part? multipart with text/html? attachments, etc?) you may or may not have any "parts" in your email.payload and instead you'll have what you're looking for in "email.payload.body.data" (for single-part messages). This is all assuming you're doing a message.get with the default format ("full"). If you instead want to get the entire email in the message.raw field and deal with it in email libraries for your language you can call message.get(format=raw).
For more info check out the "body" and "parts[]" field documentation for "Message" at https://developers.google.com/gmail/api/v1/reference/users/messages
Ah! I figured it out. parts is an array, so I should have been calling it like: gapi.client.gmail.users.messages.get({'id': <message ID>}).payload.parts[0].body.data
Now my problem is decoding the emails, which is proving successful in plain text emails, but failing in emails from non-personal locations (businesses, social media update emails, etc.). But I'll make a new question to get answers for that.
You need to search where the body for a given mime type is, I have written a recursive function for that:
function searchBodyRec(payload, mimeType){
if (payload.body && payload.body.size && payload.mimeType === mimeType) {
return payload.body.data;
} else if (payload.parts && payload.parts.length) {
return payload.parts.flatMap(function(part){
return searchBodyRec(part, mimeType);
}).filter(function(body){
return body;
});
}
}
So now you can call
var encodedBody = searchBodyRec(this.message.payload, 'text/plain');
See the flatMap method up there? Classic FP method missing in js, here is how to add it (or you can use lodash.js, or underscore.js if you don't want to mess with the native objects)
Array.prototype.flatMap = function(lambda) {
return Array.prototype.concat.apply([], this.map(lambda));
};

export Data in localStorage for later re-import

I want to export a few items from my localStorage to save it externally but in a format so that I can import it again later.
My attempt was to write executable code that can be pasted later in a textarea. Then the value of that textare will simply be eval()ed.
Problem: The data stored in localStorage were stored as
var data = [];
data.push('sampledata');
data.push({sample: 'object'});
localStorage.setItem('varname',data);
So it contains various chars I don't like, like ', " etc
My (not working) solution so far was:
var container = $('#localDataContainer');
container.append('localStorage.setItem("cockpitLastVisited","' + localStorage.getItem("cockpitLastVisited") + '");<br/>');
container.append('localStorage.setItem("cockpit_services","' + localStorage.getItem("cockpit_services") + '");<br/>');
container.append('localStorage.setItem("cockpit_users","' + localStorage.getItem("cockpit_users") + '");');
If my attempt seems to be OK, what is the best way to create code that can then be executed the way it is?
Here's how to import/export your entire localStorage
Export
copy(JSON.stringify(localStorage));
This will copy your localStorage to your clipboard. (You need two JSON.stringify()'s to get the quotes escaped.)
Import
var data = JSON.parse(/*paste stringified JSON from clipboard*/);
Object.keys(data).forEach(function (k) {
localStorage.setItem(k, JSON.stringify(data[k]));
});
Just an improved version of Jeremy. To simplify the process
copy('var data = '+JSON.stringify(localStorage)+';Object.keys(data).forEach(function (k){localStorage.setItem(k, data[k]);});');
Run this in console where you need to export, it copies localstorage content along with code to clipboard and just paste it in the console where you want to import.
You can encode Objects into Strings using JSON.stringify (object to String) and decode Strings into Objects using JSON.parse (String to Object).
Write to localStorage
localStorage.setItem("varname",JSON.stringify(originalVarname));
Read from localStorage
var originalVarname= JSON.parse(localStorage.getItem("varname"));
Export
copy(JSON.stringify(JSON.stringify(localStorage)));
Import
var data = JSON.parse(/*previously copied stringified JSON from clipboard*/);
Object.keys(data).forEach(function (k) {
localStorage.setItem(k, data[k]);
});
Just a modernized version of #iceLord answer.
Just run this in the console, it will put the code to restore the localStorage back into your clipboard.
copy(`Object.entries(${JSON.stringify(localStorage)})
.forEach(([k,v])=>localStorage.setItem(k,v))`)
Bookmarklet version
javascript:prompt(`localStorage from ${location.host}${new Date().toLocaleString()}`, `/* localStorage from ${location.host}${new Date().toLocaleString()}*/Object.entries( ${JSON.stringify(localStorage)}).forEach(([k,v])=>localStorage.setItem(k,v))`)

Categories

Resources