Reputation: 5566
I'm writing a Chrome browser extension to receive a list of URLs and download their targets using the chrome.download API, like a lighter version of Firefox's DownThemAll. I'm sure I've used sites and apps where you can paste your input, and it'll process it into separate lines:
Similar to this but without needing the add button
This is the list entry on keep.google.com, which splits on hitting enter but not for pasted content. List items can be multiline strings
Since I can't find any examples of this behaviour, I'm wondering how I'm best going about this, and hoping there might be some precedent here on SO I can't find.
My current idea is to use a textarea, and prepending a HTML5 <input type="url">
element when detecting (since these automatically validate the string as a URL). <input>
doesn't support multiple lines, and strips them out, hence having to use textarea.
My initial idea was to use the onpaste
or onkeydown({comma or newline})
. I think this is a better solution than just listening for any change to the element (and I can't see anything this approach would miss). For onpaste
the textarea would use RegEx split for /\n|,/g
and all but the last element in this array made into <input>
elements (the last remaining the textarea).
Before/while I go ahead and put this together, I'm just curious if there are any bright ideas or earlier examples - anything would be appreciated.
P.S. No JQuery plz!
Upvotes: 0
Views: 346
Reputation: 5566
Hm this is getting downvoted even though it's never been asked before and is kind of common and useful... My code to do this for anyone looking for the same solution was:
function pasteIn(e) {
txt = document.querySelector('#txtin');
setTimeout(function(){
temparray = []; tabUrls = [];
temparray.push(txt.value.replace(/,\s|\r|\f/g,'\n').replace(/\n{2,}/g,'\n').split('\n'));
for (k=0;k<temparray[0].length;k++) {
tabUrls.push(temparray[0][k]);
}
URLn = tabUrls[tabUrls.length-1];
if (!isURL(URLn)) {
(URLn == '' || URLn == ' ' || URLn == '\t') ? txt.value = null : txt.value = URLn;
tabUrls.pop([tabUrls.length]);
}
else txt.value = null;
urlHolder = document.createElement('div');
document.body.appendChild(urlHolder);
for (i=0;i<tabUrls.length;i++) {
urlbox = document.createElement('input');
urlbox.type = 'url';
urlbox.value = tabUrls[i];
document.querySelector('#main').insertBefore(urlbox,document.querySelector('textarea'));
}
}, 0);
}
function enterUp(e) {
if (e.keyCode === 13) {
console.log("Logging this one");
pasteIn();
}
}
...
document.querySelector('textarea').addEventListener('paste', pasteIn, false);
document.querySelector('textarea').addEventListener('keyup', enterUp, false);
It's up on GitHub here and being used in this browser extension.
I'm more interested in best practices than just any old fix, so leaving this question open if anyone wants to add to/critique this.
Upvotes: 1