TreeWalker in Chrome Extension - javascript

I have a Chrome extension that replaces a phone number with an ahref tag. In this ahref tag I want to call a javascript function. To simplify I'm using "javascript:alert('hey')" as the href value. When I execute the below I get "regs is not defined" for the alert function but for the console.log it displays the correct value. I tried to append to an existing questions since it's related but someone deleted it and asked that I post a new question.
Chrome extension, making a link from key words in the body
var re = /(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]??)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]??|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})/
var regs;
var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, function(node) {
if((regs = re.exec(node.textContent))) {
// make sure the text nodes parent doesnt have an attribute we add to know its all ready been highlighted
if(!node.parentNode.classList.contains('highlighted_text')) {
var match = document.createElement('A');
match.appendChild(document.createTextNode(regs[0]));
console.log(regs[0]);
match.href = "javascript:alert(regs[0])";
console.log(node.nodeValue);
// add an attribute so we know this element is one we added
// Im using a class so you can target it with css easily
match.classList.add('highlighted_text');
var after = node.splitText(regs.index);
after.nodeValue = after.nodeValue.substring(regs[0].length);
node.parentNode.insertBefore(match, after);
}
}
return NodeFilter.FILTER_SKIP;
}, false);
// Make the walker step through the nodes
walker.nextNode();

I ended up using the onclick but now I'm running into problems using XMLhttpRequest with a different domain than the one its being called from. Origin ... is not allowed by Access-Control-Allow-Origin.
Here's the code I used for the onclick event:
match.setAttribute("onclick", "function make_call(extension, phone) { xmlhttp=new XMLHttpRequest();xmlhttp.open('GET','http://[Domain]/click2call.php?extension='+extension+'&phone='+phone,false); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlhttp.send(null); } ; make_call('210','"+regs[0]+"'); return false; ");
I'm going to see about using addEventListener instead of using the above method.

We got this working using the following code.
match.setAttribute("title", regs[0]);
match.href = "#";
match.addEventListener("click", function(){ make_call('210',this.title); }, false);
We then use an XMLHttpRequest that will pass the extension and phone number to an external script that is responsible for making the call.
The only problem we have now is that it doesn't work with phone numbers found in gmail or google maps.

Related

How to call a function with an event handler if the function requires the event to compile

I am currently working on a project where I need to call a script function on an event. This function is called when text is pasted into a textarea. The function copies the pasted text into an array and iterates through the array looking for the code value of Unicode right apostrophe (8217). It then replaces any found right apostrophe's with a single quote. The function works as expected. However I am running this function on 8 different pages and want to clean my code up. I placed the script into a js file that is called on every page in the project so if any more cases it is needed are found it will be easy to implement.
The function is being called with:
<script>
var instructions = document.getElementById("specialInstructions");
instructions.addEventListener("paste", pasteToPlainText);
</script>
The function in the js file is:
function pasteToPlainText(event){
var plainText;
var replaceList;
replaceList = new Array();
//converts the pasted text to plain text
if (event.clipboardData && event.clipboardData.getData){
plainText = event.currentTarget.clipboardData.getData('text/plain');
}else if (window.clipboardData){
plainText = event.currentTarget.clipboardData.getData('text/plain');
}
for (var index = 0; index < plainText.length; index++){
var rightApostropheCheck = plainText.charCodeAt(index);
//Unicode for right apostrophe is 8217 (Used in outlook email)
//Without this conversion a right apostrophe is put on screen.
// The note is unable to save with a right apostrophe
if (rightApostropheCheck == 8217){
// replaces a right apostrophe with a single quote (apostrophe)
replaceList.push("'");
}else{
// pushes all other text to the list that is printed to screen
replaceList.push(plainText[index]);
}
}
event.preventDefault();
if (event.clipboardData) {
content = replaceList.join("");
document.execCommand('insertText', false, content);
}else if (window.clipboardData) {
content = replaceList.join("");
document.selection.createRange().pasteHTML(content);
}
}
I get the error: Uncaught TypeError: Cannot read properties of undefined (reading 'clipboardData')
On the first if statement.
Any help or advice will be greatly appreciated. Thank you.
Update:
I found a solution. making the event listener with a bind statement makes sure the function is not called on load. That was the problem as the page loaded the function was called without any information. so it had undefined errors and null errors. The correct way to call the function is as follows.
<script>
var terms = document.getElementById("Terms");
terms.addEventListener("paste", pasteToPlainText.bind(terms));
</script>

Copy rendered html with styles to outlook [duplicate]

Is there a way in javascript to copy an html string (ie <b>xx<b>) into the clipboard as text/html, so that it can then be pasted into for example a gmail message with the formatting (ie, xx in bold)
There exists solutions to copy to the clipboard as text (text/plain) for example https://stackoverflow.com/a/30810322/460084 but not as text/html
I need a non flash, non jquery solution that will work at least on IE11 FF42 and Chrome.
Ideally I would like to store both text and html versions of the string in the clipboard so that the right one can be pasted depending if the target supports html or not.
Since this answer has gotten some attention, I have completely rewritten the messy original to be easier to grasp. If you want to look at the pre-revisioned version, you can find it here.
The boiled down question:
Can I use JavaScript to copy the formatted output of some HTML code to the users clipboard?
Answer:
Yes, with some limitations, you can.
Solution:
Below is a function that will do exactly that. I tested it with your required browsers, it works in all of them. However, IE 11 will ask for confirmation on that action.
Explanation how this works can be found below, you may interactively test the function out in this jsFiddle.
// This function expects an HTML string and copies it as rich text.
function copyFormatted (html) {
// Create container for the HTML
// [1]
var container = document.createElement('div')
container.innerHTML = html
// Hide element
// [2]
container.style.position = 'fixed'
container.style.pointerEvents = 'none'
container.style.opacity = 0
// Detect all style sheets of the page
var activeSheets = Array.prototype.slice.call(document.styleSheets)
.filter(function (sheet) {
return !sheet.disabled
})
// Mount the container to the DOM to make `contentWindow` available
// [3]
document.body.appendChild(container)
// Copy to clipboard
// [4]
window.getSelection().removeAllRanges()
var range = document.createRange()
range.selectNode(container)
window.getSelection().addRange(range)
// [5.1]
document.execCommand('copy')
// [5.2]
for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = true
// [5.3]
document.execCommand('copy')
// [5.4]
for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = false
// Remove the container
// [6]
document.body.removeChild(container)
}
Explanation:
Look into the comments in the code above to see where you currently are in the following process:
We create a container to put our HTML code into.
We style the container to be hidden and detect the page's active stylesheets. The reason will be explained shortly.
We put the container into the page's DOM.
We remove possibly existing selections and select the contents of our container.
We do the copying itself. This is actually a multi-step process:
Chrome will copy text as it sees it, with applied CSS styles, while other browsers will copy it with the browser's default styles.
Therefore we will disable all user styles before copying to get the most consistent result possible.
Before we do this, we prematurely execute the copy command.
This is a hack for IE11: In this browser, the copying must be manually confirmed once. Until the user clicked the "Confirm" button, IE users would see the page without any styles. To avoid this, we copy first, wait for confirmation, then disable the styles and copy again. That time we won't get a confirmation dialog since IE remembers our last choice.
We actually disable the page's styles.
Now we execute the copy command again.
We re-enable the stylesheets.
We remove the container from the page's DOM.
And we're done.
Caveats:
The formatted content will not be perfectly consistent across browsers.
As explained above, Chrome (i.e. the Blink engine) will use a different strategy than Firefox and IE: Chrome will copy the contents with their CSS styling, but omitting any styles that are not defined.
Firefox and IE on the other hand won't apply page-specific CSS, they will apply the browser's default styles. This also means they will have some weird styles applied to them, e.g. the default font (which is usually Times New Roman).
For security reasons, browsers will only allow the function to execute as an effect of a user interaction (e.g. a click, keypress etc.)
There is a much simpler solution. Copy a section of your page (element) than copying HTML.
With this simple function you can copy whatever you want (text, images, tables, etc.) on your page or the whole document to the clipboard.
The function receives the element id or the element itself.
function copyElementToClipboard(element) {
window.getSelection().removeAllRanges();
let range = document.createRange();
range.selectNode(typeof element === 'string' ? document.getElementById(element) : element);
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
How to use:
copyElementToClipboard(document.body);
copyElementToClipboard('myImageId');
If you want to use the new Clipboard API, use the write method like below:
var type = "text/html";
var blob = new Blob([text], { type });
var data = [new ClipboardItem({ [type]: blob })];
navigator.clipboard.write(data).then(
function () {
/* success */
},
function () {
/* failure */
}
);
Currently(Sep 2021), The problem is that Firefox doesn't support this method.
I have done a few modifications on Loilo's answer above:
setting (and later restoring) the focus to the hidden div prevents FF going into endless recursion when copying from a textarea
setting the range to the inner children of the div prevents chrome inserting an extra <br> in the beginning
removeAllRanges on getSelection() prevents appending to existing selection (possibly not needed)
try/catch around execCommand
hiding the copy div better
On OSX this will not work. Safari does not support execCommand and chrome OSX has a known bug https://bugs.chromium.org/p/chromium/issues/detail?id=552975
code:
clipboardDiv = document.createElement('div');
clipboardDiv.style.fontSize = '12pt'; // Prevent zooming on iOS
// Reset box model
clipboardDiv.style.border = '0';
clipboardDiv.style.padding = '0';
clipboardDiv.style.margin = '0';
// Move element out of screen
clipboardDiv.style.position = 'fixed';
clipboardDiv.style['right'] = '-9999px';
clipboardDiv.style.top = (window.pageYOffset || document.documentElement.scrollTop) + 'px';
// more hiding
clipboardDiv.setAttribute('readonly', '');
clipboardDiv.style.opacity = 0;
clipboardDiv.style.pointerEvents = 'none';
clipboardDiv.style.zIndex = -1;
clipboardDiv.setAttribute('tabindex', '0'); // so it can be focused
clipboardDiv.innerHTML = '';
document.body.appendChild(clipboardDiv);
function copyHtmlToClipboard(html) {
clipboardDiv.innerHTML=html;
var focused=document.activeElement;
clipboardDiv.focus();
window.getSelection().removeAllRanges();
var range = document.createRange();
range.setStartBefore(clipboardDiv.firstChild);
range.setEndAfter(clipboardDiv.lastChild);
window.getSelection().addRange(range);
var ok=false;
try {
if (document.execCommand('copy')) ok=true; else utils.log('execCommand returned false !');
} catch (err) {
utils.log('execCommand failed ! exception '+err);
}
focused.focus();
}
see jsfiddle where you can enter html segment into the textarea and copy to the clipboard with ctrl+c.
For those looking for a way to do this using ClipboardItem and cannot get it to work even with dom.events.asyncClipboard.clipboardItem set to true, the answer can be found at nikouusitalo.com.
And here is my working code (tested on Firefox 102).
const clipboardItem = new
ClipboardItem({'text/html': new Blob([html],
{type: 'text/html'}),
'text/plain': new Blob([html],
{type: 'text/plain'})});
navigator.clipboard.write([clipboardItem]).
then(_ => console.log("clipboard.write() Ok"),
error => alert(error));
Make sure you try pasting it into a rich text editor such as gmail and not to a plain text/markdown editor such as stackoverflow.

Javascript - Copy string to clipboard as text/html

Is there a way in javascript to copy an html string (ie <b>xx<b>) into the clipboard as text/html, so that it can then be pasted into for example a gmail message with the formatting (ie, xx in bold)
There exists solutions to copy to the clipboard as text (text/plain) for example https://stackoverflow.com/a/30810322/460084 but not as text/html
I need a non flash, non jquery solution that will work at least on IE11 FF42 and Chrome.
Ideally I would like to store both text and html versions of the string in the clipboard so that the right one can be pasted depending if the target supports html or not.
Since this answer has gotten some attention, I have completely rewritten the messy original to be easier to grasp. If you want to look at the pre-revisioned version, you can find it here.
The boiled down question:
Can I use JavaScript to copy the formatted output of some HTML code to the users clipboard?
Answer:
Yes, with some limitations, you can.
Solution:
Below is a function that will do exactly that. I tested it with your required browsers, it works in all of them. However, IE 11 will ask for confirmation on that action.
Explanation how this works can be found below, you may interactively test the function out in this jsFiddle.
// This function expects an HTML string and copies it as rich text.
function copyFormatted (html) {
// Create container for the HTML
// [1]
var container = document.createElement('div')
container.innerHTML = html
// Hide element
// [2]
container.style.position = 'fixed'
container.style.pointerEvents = 'none'
container.style.opacity = 0
// Detect all style sheets of the page
var activeSheets = Array.prototype.slice.call(document.styleSheets)
.filter(function (sheet) {
return !sheet.disabled
})
// Mount the container to the DOM to make `contentWindow` available
// [3]
document.body.appendChild(container)
// Copy to clipboard
// [4]
window.getSelection().removeAllRanges()
var range = document.createRange()
range.selectNode(container)
window.getSelection().addRange(range)
// [5.1]
document.execCommand('copy')
// [5.2]
for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = true
// [5.3]
document.execCommand('copy')
// [5.4]
for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = false
// Remove the container
// [6]
document.body.removeChild(container)
}
Explanation:
Look into the comments in the code above to see where you currently are in the following process:
We create a container to put our HTML code into.
We style the container to be hidden and detect the page's active stylesheets. The reason will be explained shortly.
We put the container into the page's DOM.
We remove possibly existing selections and select the contents of our container.
We do the copying itself. This is actually a multi-step process:
Chrome will copy text as it sees it, with applied CSS styles, while other browsers will copy it with the browser's default styles.
Therefore we will disable all user styles before copying to get the most consistent result possible.
Before we do this, we prematurely execute the copy command.
This is a hack for IE11: In this browser, the copying must be manually confirmed once. Until the user clicked the "Confirm" button, IE users would see the page without any styles. To avoid this, we copy first, wait for confirmation, then disable the styles and copy again. That time we won't get a confirmation dialog since IE remembers our last choice.
We actually disable the page's styles.
Now we execute the copy command again.
We re-enable the stylesheets.
We remove the container from the page's DOM.
And we're done.
Caveats:
The formatted content will not be perfectly consistent across browsers.
As explained above, Chrome (i.e. the Blink engine) will use a different strategy than Firefox and IE: Chrome will copy the contents with their CSS styling, but omitting any styles that are not defined.
Firefox and IE on the other hand won't apply page-specific CSS, they will apply the browser's default styles. This also means they will have some weird styles applied to them, e.g. the default font (which is usually Times New Roman).
For security reasons, browsers will only allow the function to execute as an effect of a user interaction (e.g. a click, keypress etc.)
There is a much simpler solution. Copy a section of your page (element) than copying HTML.
With this simple function you can copy whatever you want (text, images, tables, etc.) on your page or the whole document to the clipboard.
The function receives the element id or the element itself.
function copyElementToClipboard(element) {
window.getSelection().removeAllRanges();
let range = document.createRange();
range.selectNode(typeof element === 'string' ? document.getElementById(element) : element);
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
How to use:
copyElementToClipboard(document.body);
copyElementToClipboard('myImageId');
If you want to use the new Clipboard API, use the write method like below:
var type = "text/html";
var blob = new Blob([text], { type });
var data = [new ClipboardItem({ [type]: blob })];
navigator.clipboard.write(data).then(
function () {
/* success */
},
function () {
/* failure */
}
);
Currently(Sep 2021), The problem is that Firefox doesn't support this method.
I have done a few modifications on Loilo's answer above:
setting (and later restoring) the focus to the hidden div prevents FF going into endless recursion when copying from a textarea
setting the range to the inner children of the div prevents chrome inserting an extra <br> in the beginning
removeAllRanges on getSelection() prevents appending to existing selection (possibly not needed)
try/catch around execCommand
hiding the copy div better
On OSX this will not work. Safari does not support execCommand and chrome OSX has a known bug https://bugs.chromium.org/p/chromium/issues/detail?id=552975
code:
clipboardDiv = document.createElement('div');
clipboardDiv.style.fontSize = '12pt'; // Prevent zooming on iOS
// Reset box model
clipboardDiv.style.border = '0';
clipboardDiv.style.padding = '0';
clipboardDiv.style.margin = '0';
// Move element out of screen
clipboardDiv.style.position = 'fixed';
clipboardDiv.style['right'] = '-9999px';
clipboardDiv.style.top = (window.pageYOffset || document.documentElement.scrollTop) + 'px';
// more hiding
clipboardDiv.setAttribute('readonly', '');
clipboardDiv.style.opacity = 0;
clipboardDiv.style.pointerEvents = 'none';
clipboardDiv.style.zIndex = -1;
clipboardDiv.setAttribute('tabindex', '0'); // so it can be focused
clipboardDiv.innerHTML = '';
document.body.appendChild(clipboardDiv);
function copyHtmlToClipboard(html) {
clipboardDiv.innerHTML=html;
var focused=document.activeElement;
clipboardDiv.focus();
window.getSelection().removeAllRanges();
var range = document.createRange();
range.setStartBefore(clipboardDiv.firstChild);
range.setEndAfter(clipboardDiv.lastChild);
window.getSelection().addRange(range);
var ok=false;
try {
if (document.execCommand('copy')) ok=true; else utils.log('execCommand returned false !');
} catch (err) {
utils.log('execCommand failed ! exception '+err);
}
focused.focus();
}
see jsfiddle where you can enter html segment into the textarea and copy to the clipboard with ctrl+c.
For those looking for a way to do this using ClipboardItem and cannot get it to work even with dom.events.asyncClipboard.clipboardItem set to true, the answer can be found at nikouusitalo.com.
And here is my working code (tested on Firefox 102).
const clipboardItem = new
ClipboardItem({'text/html': new Blob([html],
{type: 'text/html'}),
'text/plain': new Blob([html],
{type: 'text/plain'})});
navigator.clipboard.write([clipboardItem]).
then(_ => console.log("clipboard.write() Ok"),
error => alert(error));
Make sure you try pasting it into a rich text editor such as gmail and not to a plain text/markdown editor such as stackoverflow.

How does the `data-include` attribute likely work?

I'm analyzing a site and I see that there is a data-include attribute on a div.
I see that data- is part of the HTML 5 spec according to a Resig article.
I can also see that the div is being replaced by some response HTML as it fires off an xhr request to the server. This mechanism is basically used to load modules client side.
<div data-include='some.path'></div>
The question I have is how is the XHR fired off?
I'm used to accessing the DOM via IDs # or classes ., or selectors of some sort.
I see no selector so I can't figure out how it is done?
Here is a list of js according to Chrome
data-include is used by csi.js -- client side includes. An element with data-include='URL' is automatically replaced with the contents of the URL.
You can select DOM elements by data attribute, either by their value or just the presence of them. For example, using jQuery, this selector would give you all the elements with a data-include attribute: $("[data-include]"). So roughly if you wanted to load a bunch of URL's given by the data-attribute data-include in a bunch of divs, you could do something like this.
$('[data-include]').each( function() {
var path = $(this).data('include');
// Do something with this path
});
That is how you would gather up those elements, then I assume you loop through them and load the scripts from that attribute. Does that answer your question?
After looking at the source code of csi.js, I learned that this is how it's done:
window.onload = function() {
var elements = document.getElementsByTagName('*'),
i;
for (i in elements) {
if (elements[i].hasAttribute && elements[i].hasAttribute('data-include')) {
fragment(elements[i], elements[i].getAttribute('data-include'));
}
}
function fragment(el, url) {
var localTest = /^(?:file):/,
xmlhttp = new XMLHttpRequest(),
status = 0;
xmlhttp.onreadystatechange = function() {
/* if we are on a local protocol, and we have response text, we'll assume things were sucessful */
if (xmlhttp.readyState == 4) {
status = xmlhttp.status;
}
if (localTest.test(location.href) && xmlhttp.responseText) {
status = 200;
}
if (xmlhttp.readyState == 4 && status == 200) {
el.outerHTML = xmlhttp.responseText;
}
}
try {
xmlhttp.open("GET", url, true);
xmlhttp.send();
} catch(err) {
/* todo catch error */
}
}
}
He basically just uses vanilla JS and grabs all the elements, loops through them to see which have the attribute of data-include and then makes a new http request for each attribute that he finds. It's really straight forward and could be written way shorter in jQuery, but it's not necessary since you would have to include a whole library for such a simple task.
Nowadays, many JS libraries use whatever- prefixes to many things. Check what library the site is using and then read it's documentation to understand why it's there.

using popupNode in a javascript firefox extension

I am trying to use popupNode in a little javascript based firefox extension. So if a user right click on a link and then clicks on an additional menu item a new tab opens with the link (sorta like "open in new tab"):
`
var foo = {
onLoad: function() {
// initialization code
this.initialized = true;
},
onMenuItemCommand: function() {
var tBrowser = document.getElementById("content");
var target = document.popupNode;
tBrowser.selectedTab = tab;
var tab = tBrowser.addTab(target);
}
};
window.addEventListener("load", function(e) { foo.onLoad(e); }, false);
`
It works mostly, but I am wondering in that is the right use. The problem is I want replace some characters on the var target, but somehow that partdoes not work. something like target.replace() will cause problems. So I am guessing target is not a string.
Mostly I would like to know what popupNode actually does ...
thanks
Peter
I haven't really used "popupNode", but in general nodes aren't the same as strings. I suggest reading up on the Document Object Model (DOM) to learn more.
As far as replacing text, assuming popupNodes work like other nodes then something like this may work for you:
var target = document.popupNode;
target.innerHTML = target.innerHTML.replace("old_string", "new_string")

Categories

Resources