Google Apps Script problem using getLinkUrl(offset) - javascript

I'm trying to figure out how to use getLinkUrl(offset) in Google Apps Script.
I found the reference here - http://googlescriptreference.com/Document/Text/getlinkurloffset/, but I can't find any examples online.
This GAS returns Paragraphin the logs
var paragraph = tableCell.getChild(0);
This GAS returns the text string in the paragraph in the logs
var paragraphText = paragraph.getText();
This GAS returns NULL in the logs
var paragraphText = paragraph.getLinkUrl();
This GAS returns an error ( Cannot find method getLinkUrl(number).) and nothing in the logs
var paragraphText = paragraph.getLinkUrl(2);
Can someone please help me understand how to use the getLinkUrl(offset)?
Thanks for your help!

I was attempting to use the getLinkUrl(offset) directly on the paragraph element (not working example), but I needed to use asText() method before getLinkUrl(offset).
NOT Working
var paragraphText = paragraph.getLinkUrl(2);
Working
var paragraphText = paragraph.asText().getLinkUrl(2);
Google Document
https://docs.google.com/document/d/136G549zIYPYBndXs70ZnR_wEFg5fPST9ZGsOlTgmDyM/edit
//Works if link is on a word or words instead of entire paragraph
function myFunctionP1() {
//Find out how many Children there are
var body = DocumentApp.getActiveDocument().getBody();
Logger.log(body.getNumChildren());
//Find out which child is table
var table = body.getChild(2); //table is child#2
Logger.log(table);
//Find tableCell inside of table
var tableCell = table.getChild(0).getChild(0); //tableCell
Logger.log(tableCell)
//Find paragraph inside of tableCell
//I think, but I'm not sure, the HYPERLINK will be found somewhere within the PARAGRAPH element. But I can't figure out how to get to it.
var paragraph = tableCell.getChild(0); //paragraph element
Logger.log(paragraph)
//Get paragraph text
var paragraphText = paragraph.asText().getLinkUrl(2); //paragraph text
Logger.log(paragraphText)
}
//Works if link is on entire paragraph
//Works if link is on entire paragraph
//Works if link is on entire paragraph
function myFunctionP2() {
//Find out how many Children there are
var body = DocumentApp.getActiveDocument().getBody();
Logger.log(body.getNumChildren());
//Find out which child is table
var table = body.getChild(4); //table is child#2
Logger.log(table);
//Find tableCell inside of table
var tableCell = table.getChild(0).getChild(0); //tableCell
Logger.log(tableCell)
//Find paragraph inside of tableCell
//I think, but I'm not sure, the HYPERLINK will be found somewhere within the PARAGRAPH element. But I can't figure out how to get to it.
var paragraph = tableCell.getChild(0); //paragraph element
Logger.log(paragraph)
//Get paragraph text
var paragraphText = paragraph.getText(); //paragraph text
Logger.log(paragraphText)
//Get HYPERLIINK from paragraph text
var paragraphHYPERLINK = paragraph.getLinkUrl(); //paragraph text
Logger.log(paragraphHYPERLINK)
}
#Tanaike helped me find this solution.
https://stackoverflow.com/users/7108653/tanaike

Related

Wrapping a DIV around a hyperlink created using appendChild

I have a bit of JS to add an email hyperlink to a page, after a DIV with an ID value of section_form_id:
// build email
var elmNewContentCustomer = document.createElement('a');
var elmFoo = document.getElementById('section_form_id');
elmNewContentCustomer.href = 'mailto:me#example.com?subject=Something';
elmNewContentCustomer.setAttribute("style", "color:blue;");
elmNewContentCustomer.setAttribute("id", "email_customer_id");
elmNewContentCustomer.appendChild(document.createTextNode('Email Customer'));
elmFoo.parentNode.insertBefore(elmNewContentCustomer, elmFoo.nextSibling);
This works fine. However, I'd like to put the hyperlink inside a DIV so I set the style attributes of the DIV.
I tried using this method, which was to create a DIV, and insert it before the email block using appendChild but it doesn't work:
var elmNewEmailDev = document.createElement('div');
var elmFoo2 = document.getElementById('email_customer_id');
elmNewEmailDev.setAttribute("style", "background:yellow;");
elmNewEmailDev.appendChild(elmFoo.parentNode.insertBefore(elmNewContentCustomer, elmFoo.nextSibling));
elmFoo2.parentNode.insertBefore(elmNewEmailDev, elmFoo.elmFoo2);
How can I wrap a DIV around the hyperlink so I can then use setAttribute to be able to control the style of that DIV?
Follow this method your get result as you want.
var myEmailLink = "<a href='mailto:a#b.com'>a#b.com</a>";
var myDiv = document.getElementById("section_form_id");
myDiv.insertAdjacentHTML('afterEnd', myEmailLink )
<div id="section_form_id">
My Div Here
</div>

On search/highlight click -> existing div becomes wrapped with existing span

I have a problem with javascript search and highlight text.
For example, there is existing span element and existing div element.
Problem is that if I click on search button for some reason div element becomes a child of span element.
To explain it better I have created JS fiddle to show the problem:
function highlightSearch() {
$('span').removeClass('highlighted');
var text = document.getElementById('query').value;
var query = new RegExp("(\\b" + text + "\\b(?!([^<]+)?>))", "gim");
var e = document.getElementById("searchText").innerHTML;
var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");
document.getElementById("searchText").innerHTML = enew;
var newe = enew.replace(query, "<span class='highlighted'>$1</span>");
document.getElementById("searchText").innerHTML = newe;
}
Check problem on : JSfiddle
Well, you are removing all </span> tags from the innerHTML in this line:
var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");
And therefore also the </span> of .glyphicon. This is why the element becomes wrapped.
Btw: An exception is thrown: ReferenceError: highlightSearch is not defined

Appending Paragraph at specific location

I need to be able to change a string of text to heading1 and do some additional formatting later on. Caught up on this part for now. Here is my sample code as of right now.
function pocket() {
// Try to get the current selection in the document. If this fails (e.g.,
// because nothing is selected), show an alert and exit the function.
var selection = DocumentApp.getActiveDocument().getSelection();
var body = DocumentApp.getActiveDocument().getBody();
if (!selection) {
DocumentApp.getUi().alert('Cannot find a selection in the document.');
return;
}
var selectedElements = selection.getSelectedElements();
var selectedElement = selectedElements[0];
var pocketelement = selectedElement.getElement().getText();
body.appendParagraph(pocketelement).setHeading(DocumentApp.ParagraphHeading.HEADING1);
}
I need it to delete the original string and append the paragraph at the original strings location. Not sure how to do that. any help will be appreciated!
The body.appendParagraph() method appends the given paragraph, like javascript, to the body, at the end of it.
You are looking for the .insertParagraph(index, Paragraph). To get the index, try body.getChildIndex(paragraph). See the code below.
function pocket() {
// Try to get the current selection in the document. If this fails (e.g.,
// because nothing is selected), show an alert and exit the function.
var doc = DocumentApp.getActiveDocument();
var selection = doc.getSelection();
var body = doc.getBody();
if (!selection) {
DocumentApp.getUi().alert('Cannot find a selection in the document.');
return;
}
var selectedElements = selection.getSelectedElements();
var selectedElement = selectedElements[0];
//holds the paragraph
var paragraph = selectedElement.getElement();
//get the index of the paragraph in the body
var paragraphIndex = body.getChildIndex(paragraph);
//remove the paragraph from the document
//to use the insertParagraph() method the paragraph to be inserted must be detached from the doc
paragraph.removeFromParent();
body.insertParagraph(paragraphIndex, paragraph).setHeading(DocumentApp.ParagraphHeading.HEADING1);
};

Not able to append an img tag to a p tag

I'm a complete beginner in JavaScript and I am trying to create a script which is fired when a "file input" element of the page gets a file loaded. The script should basically create a p element, insert in it an img, a innerText and a span, hence append all this into a form. Everything works fine with the script below, except for the img:
function visualUploadFile() {
var obj = document.getElementById("hidden_file").files[0].name;
//create p object to append to the form
var pobj = document.createElement("p");
pobj.className = "form_line_file";
//nest icon inside the object
var imgico = document.createElement("img");
imgico.src = "load-ico.png";
//append img to the p - THE OBJECT IS NOT APPENDED
pobj.appendChild(imgico);
//nest file name as inner Text to the p
pobj.innerText = obj;
//create span object to write "rimuovi"
var spanobj = document.createElement("span");
spanobj.className = "rimuovi_file";
spanobj.innerHTML = "rimuovi";
//append span to the p
pobj.appendChild(spanobj);
//get form and append p child
var bigForm = document.getElementById("offerta_form");
bigForm.appendChild(pobj);
}
Here is the HTML after the script has been executed, as you can see only the img is missing:
<p class="form_line_file"> <!--p object correctly appended to the form-->
Immagine.png <!--inner Text properly appended-->
<span class="rimuovi_file"> <!--span object correctly appended-->
rimuovi
</span>
</p>
Probably is a stupid mistake, but I'm not being able to sort it out. Could anyone please tell me what I'm doing wrong not to be able to get the img appended as for the span?
The way you are adding file name label is incorrect. Setting innerText overwrites image. Instead of
pobj.innerText = obj;
try this:
pobj.appendChild(document.createTextNode(obj));

how to select a text range in CKEDITOR programatically?

Problem:
I have a CKEditor instance in my javascript:
var editor = CKEDITOR.instances["id_corpo"];
and I need to insert some text programatically, and select some text range afterwards.
I already did insert text through
editor.insertHtml('<h1 id="myheader">This is a foobar header</h1>');
But I need to select (highlight) the word "foobar", programatically through javascript, so that I can use selenium to work out some functional tests with my CKEditor plugins.
UPDATE 1:
I've also tried something like
var selection = editor.getSelection();
var childs = editor.document.getElementsByTag("p");
selection.selectElement(childs);
But doesn't work at all!
How can I do that?
I think that
selection.selectRange()
could do the job, but I'could not figure out how to use it.
There are no examples over there :(
Get current selection
var editor = CKEDITOR.instances["id_corpo"];
var sel = editor.getSelection();
Change the selection to the current element
var element = sel.getStartElement();
sel.selectElement(element);
Move the range to the text you would like to select
var findString = 'foobar';
var ranges = editor.getSelection().getRanges();
var startIndex = element.getHtml().indexOf(findString);
if (startIndex != -1) {
ranges[0].setStart(element.getFirst(), startIndex);
ranges[0].setEnd(element.getFirst(), startIndex + findString.length);
sel.selectRanges([ranges[0]]);
}
You can also do the following:
get the current selection
var selection = editor.getSelection();
var selectedElement = selection.getSelectedElement();
if nothing is selected then create a new paragraph element
if (!selectedElement)
selectedElement = new CKEDITOR.dom.element('p');
Insert your content into the element
selectedElement.setHtml(someHtml);
If needed, insert your element into the DOM (it will be inserted into the current position)
editor.insertElement(selectedElement);
and then just select it
selection.selectElement(selectedElement);
Check out the selectElement() method of CKEDITOR.dom.selection.
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.dom.selection.html
insert text at cursor point in ck editor
function insertVar(myValue) {
CKEDITOR.instances['editor1'].fire( 'insertText',myValue);
}
this is working for me

Categories

Resources