Open a Local link in a new tab - javascript

I have a scenario where I am linking all the URLs in a Text in a Hyperlink. But when a user types www., then the browser takes it as a local URL and binds the link to the applications URL.
I want to know how to open local URL in a new Tab.
var replaceTextWithURL = systemNotificationText.replace(/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi, function(text, link) {
console.log(text, link);
return ' ' + link + ' ';
//var httpUrl = link.startsWith("http");
//var httpsUrl = link.startsWith("https");
//if (httpUrl || httpsUrl) {
// return ' ' + text + ' ';
//}
//else {
// return ' ' + text + ' ';
//}
});
var newLineText = replaceTextWithURL.replace(/\r?\n/g, '<br />');
$("#systemNotificationPreview").html(newLineText);

can you refine your question, it is not pretty clear what you are asking for?

Related

email script for multiple receiver

I stuck sending mails to email script for multiple receiver
May someone could help me
var recipient2=(ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T16").getValue()) + ',' + (ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T25").getValue()) + ',' + (ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T28").getValue()) ;
it should send to 3 different mails which could change.
Any help is welcome
This is my complete code, I try to work with cc and bcc but it always send the mail only to one email
// Define your variables here
function mailPDFtoHO( optSSId, optSheetId ) {
//If a sheet ID was provided, open that sheet, otherwise assume script is
//sheet-bound, and open the active spreadsheet.
var ss = (optSSId) ? SpreadsheetApp.openById(optSSId) : SpreadsheetApp.getActiveSpreadsheet();
//Get URL of spreadsheet, and remove the trailing 'edit'
var url = ss.getUrl().replace(/edit$/,'');
//Get folder containing spreadsheet, for later export
var parents = DriveApp.getFileById(ss.getId()).getParents();
if (parents.hasNext()) {
var folder = parents.next();
}
else {
folder = DriveApp.getRootFolder();
}
//Get array of all sheets in spreadsheet
// var sheets = ss.getSheets();
//Loop through all sheets, generating PDF files.
//for (var i=0; i<sheets.length; i++) {
//var sheet = sheets[i];
//If provided a optSheetId, only save it.
//if (optSheetId && optSheetId !== sheet.getSheetId()) continue;
//additional parameters for exporting the sheet as a pdf
var url_ext = 'export?exportFormat=pdf&format=pdf' //export as pdf
//+ '&gid=' + sheet.getSheetId() //the sheet's Id
//following parameters are optional...
+ '&size=A4' //paper size
+ '&portrait=false' //orientation, false for landscape
+ '&fitw=true' //fit to width, false for actual size
+ '&sheetnames=false&printtitle=false&pagenumbers=false' //hide optional headers and footers
+ '&gridlines=false' //hide gridlines
+ '&fzr=false' //do not repeat row headers (frozen rows) on each page
+ '&gid=1672240374'
+ '&ir=false' //seems to be always false
+ '&ic=false' //same as ic
+ '&r1=1' //Start Row number - 1, so row 1 would be 0 , row 15 wold be 14
+ '&c1=0' //Start Column number - 1, so column 1 would be 0, column 8 would be 7
+ '&r2=78' //End Row number
+ '&c2=29'; //End Column number;
var options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
}
}
var response = UrlFetchApp.fetch(url + url_ext, options);
var blob = response.getBlob().setName(ss.getName() + '_' + ss.getSheetByName("Timesheet").getRange("B5").getValue() + "_" + ss.getSheetByName("Timesheet").getRange("X5").getValue() + "_" + ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T7").getValue() + "." + ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T5").getValue() + '.pdf');
//from here you should be able to use and manipulate the blob to send and email or create a file per usual.
//In this example, I save the pdf to drive
var recipient1=Session.getActiveUser().getEmail();
var recipient2=ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T16").getValue() ;
var recipient3=ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T25").getValue() ;
var recipient4=ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T28").getValue() ;
var subject1=SpreadsheetApp.getActiveSpreadsheet().getName() + ' ' + ss.getSheetByName("Timesheet").getRange("B5").getValue() + ' ' + ss.getSheetByName("Timesheet").getRange("X5").getValue() + " " + ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T7").getValue() + "/" + ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T5").getValue() ;
var subject2='FW:' + ' ' + SpreadsheetApp.getActiveSpreadsheet().getName() + ' ' + ss.getSheetByName("Timesheet").getRange("B5").getValue() + ' ' + ss.getSheetByName("Timesheet").getRange("X5").getValue() + " " + ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T7").getValue() + "/" + ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T5").getValue() ;
var body="Hello " + ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T13").getValue() + "," + "\n\nPlease find attached the timesheet for " + ss.getSheetByName("Timesheet").getRange("X5").getValue() + ".\n\nBest Regards,\n\n" + ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T10").getValue();
var message1 = {
to: recipient1,
subject: subject1,
body: body,
attachments: [blob]
}
var message2 = {
to: recipient2,
cc: recipient3,
bcc: recipient4,
subject: subject2,
body: body,
attachments: [blob]
}
var confirm1 = Browser.msgBox('send confirmation','Are you sure you want to send this mail to your mail-box?', Browser.Buttons.OK_CANCEL);
if(confirm1=='ok'){ MailApp.sendEmail(message2)};
var confirm2 = Browser.msgBox('send confirmation','Are you sure you want to send this mail to your Bundget Resposible ' + ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T19").getValue() + ' , time agent ' + ss.getSheetByName("ECA-Points & Personal Nr.").getRange("T22").getValue() + ' and DAOS?', Browser.Buttons.OK_CANCEL);
if(confirm2=='ok'){ MailApp.sendEmail(message1)};

Translate JQuery code to Javascript probleme with "prepend"

I want to translate this jquery code :
$('#zone').prepend('<p><strong>' + login + '</strong> ' + message + '</p>');
I tried that:
document.getElementById('zone').innerHTML = '<p><strong>' + login + '</strong> ' + message + '</p>';
but the problem is i don't know where i can put ".prepend".
thank you for your help
If you want to stick to innerHTML, you can just do this:
const zone = document.getElementById('zone');
zone.innerHTML = '<p><strong>' + login + '</strong> ' + message + '</p>' + zone.innerHTML;
Another idea is to use dynamic element and avoid rewriting your #zone HTML (that's important when you have things like inputs there, because the first example will clear them out):
const p = document.createElement('p');
const strong = document.createElement('strong');
strong.textContent = login;
p.append(strong, ' ' + message);
document.getElementById('zone').prepend(p);
You should add it to the beginning of the string as follows:
var zone = document.getElementById('zone');
const content = zone.innerHTML;
zone.innerHTML = `<p><strong>${login}</strong>${message}</p>` + content;
You can use Node#firstChild property and Node#inserBefore method, so it won't recreate existing child elements.
// create the `p` tag and set its HTML content
const p = document.createElemnt('p');
p.innerHTML = '<strong>' + login + '</strong> ' + message ;
const ele = document.getElementById('zone');
// insert the created p tag element before the first element
ele.insertBefore(p, ele.firstChild) ;

Hyperlink in javascript, for mail subject

I have js code that opens a mailto dialog when pressing on link, it is working as "share with a friend" function:
setTimeout( function(){
var subject, body, email_string;
subject = oScript_x.post_title;
body = "you got mail from";
//body += "link: " + "<a href='" + location.href + "'>" + location.href + " </a>";
body += "link " + location.href;
email_string = "mailto:?subject=" + subject + "&body=" + body;
email_string = email_string.replace(/ /g, "%20" ).replace(/\n/g, "%0A");
I tried to use this :
body += "link: " + "" + location.href + " ";
But no luck...
So now I am only showing the link as text with no link.
I would appreciate help to have the link clickable and under an anchor text.
Thanks
The problem is that you are not escaping things properly. Instead of manually replacing certain patterns, you should use encodeURIComponent for each of the parameters that you add.
In other words, your code should look like this:
var subject = ... // whatever you do to create this string
var body = ... // whatever you do to create this string
var encodedSubject = encodeURIComponent(subject);
var encodedBody = encodeURIComponent(body);
var emailLink = 'mailto:?subject=' + encodedSubject + '&body=' + encodedBody;
// ... use emailLink

ContextMenuItem context function is not executing

I want my context menu item to be visible only if the clicked node is a link i.e. and href is either a magnet link or a torrent link. But item is visible for all the links because context function is not executing, can anybody help why context function is not executing?
Here is the code:
exports.main = function() {
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
var clickCode = ' self.on("click", function(node,data){ '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_hash = /[0-9abcdef]{32,40}/i; ' +
' var result = node.href.match(pat_hash); '+
' var hash = "" '
' if(result != null) { hash=result[0]; } '+
' var xhr = new XMLHttpRequest(); '+
' if(hash != "") { '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&info_hash="+hash; '+
' } '+
' else{ '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&url="+encodeURI(node.href); '+
' } '+
' xhr.open("GET",apiCall,true); '+
' xhr.onreadystatechange = function(){ if(xhr.readyState = 4) { if (xhr.response.status = "ok") { alert("Torrent added to Furk."); } else { alert("Torrent could not be added to Furk."); } } } '+
' xhr.send(null); '+
' });';
cm.Item({
label: "Add to Furk",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode + clickCode
});
};
Please always post self-containied examples that can be directly tried in the future.
Now back to your problem: The content script actually has a syntax error.
The following line:
' var pat_torrent = /.torrent$/i ' +
lacks a semicolon, and should be:
' var pat_torrent = /.torrent$/i; ' +
The reason automatic semicolon insertion (ASI) does not work here is: The "code" is actually a string that has no newlines in it whatsoever. If there were newlines, then ASI would have worked.
Anway, another reason not to have complex content script inline. Have a look at contentScriptFile.
This error is actually logged, but the presentation sucks. In the Browser Console:
[20:57:51.707] [object Error] (expandable)
In terminal:
console.error: context-magnet:
Message: SyntaxError: missing ; before statement
Here is a fixed, reproducible sample:
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
cm.Item({
label: "magnet test",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode
});
Edit ' var hash = "" ' has the same problem, and there are might be other such errors that I missed skimming this new code.
As I already said, please use contentScriptFile and not contentScript for long-ish scripts.
Another edit
Here is a builder using contentScriptFile, where I also fixed a couple of other errors, the most important of which are:
Use permissions so that the XHR will work.
Correctly set up the XHR to use responseType and overrideMimeType().
Use onload/onerror instead of onreadystatechange.

javascript. my for loop stops after one iteration when enclosed in a function

here's my problem. When my code is embedded within an html page, between body tags, it executes as it's suppose to : displays 12 lines of text (for loop goes 12 times);
but, when I enclose the code in a function, import it from an external js file, and try to envoke it with an onclick or onsubmit event, it stops after the first iteration.
this is the code embedded in an html file:
var all_imgs = document.getElementsByTagName('img');
for(var i=0; i<all_imgs.length; i++){
var item = all_imgs[i].src;
var item_limit = item.length-4;
var item_limit2 = item.length-6;
var selected = item.substring(item_limit, item_limit2);
if (selected == 'on') {
document.write('image ' + i + ' with url : ' + item + ' is ');
document.write('chosen');
document.write('<br>');
}
else {
document.write('image ' + i + ' with url : ' + item + ' is ');
document.write('not chosen');
document.write('<br>');
}
}
and the output:
image 0 with url : www.../thumb2_on.jpg is CHOSEN
image 1 with url : www.../thumb2_off.jpg is NOT CHOSEN
image 2 with url : www.../thumb2_off.jpg is NOT CHOSEN
image 3 ...
.
.
.
image 11 with url : www.../thumb2_on.jpg is CHOSEN
this is the code from the external js file :
function selectedImages(){
var all_imgs = document.getElementsByTagName('img');
for(var i=0; i<all_imgs.length; i++){
var item = all_imgs[i].src;
var item_limit = item.length-4;
var item_limit2 = item.length-6;
//document.write(item_limit);
//document.write(item_limit2);
var selected = item.substring(item_limit, item_limit2);
if (selected == 'on') {
document.write('image ' + i + ' with url : ' + item + ' is ');
document.write('chosen');
document.write('<br>');
}
else {
document.write('image ' + i + ' with url : ' + item + ' is ');
document.write('not chosen');
document.write('<br>');
}
}
}
the onclick event from the html file :
test
or
<form action="#" method="post" onsubmit="javascript:selectedImages();">
and the print out :
image 0 with url : www.../thumb2_on.jpg is CHOSEN
That is because you are using document.write after the page has loaded. It will replace the current page with the new content, so when you get to the second iteration in the loop there aren't any images in the page any more.

Categories