I am creating a chrome extension. Basically, the if the user clicks a content menu option, I want to insert HTML format tags before and after the selected text.
The tags are being added in an event page which, after adding the format tags, fires off the new value to a content script in the 'paste' key of the message object.
The code for my content script is as follows:
chrome.runtime.onMessage.addListener(handleRequest)
function handleRequest(message, sender)
{
if (message.paste!==undefined)
{
var newNode = document.createTextNode('');
newNode.innerHTML=message.paste;
var cursor = window.getSelection().getRangeAt(0);
cursor.deleteContents();
cursor.insertNode(newNode);
alert(newNode.innerHTML);
}
}
I thought I was doing this correctly, because according to this
If the new node is to be added to a text Node, that Node is split at the insertion point, and the insertion occurs between the two text nodes.
However, the result of clicking the context menu option is simply the deletion whatever text was selected. The new text is never added, but no errors are printed to console.
I am aware that this will not work for stuff in input elements or text areas, right now I am just trying to get it work on regular text on the page.
The contents of the alert popup are, as expected, the selected text surrounded in formatting tags.
Can someone explain what I am doing wrong? should I not be editing the HTML of a text node? Is there some last step that I am missing to make the text appear?
Demonstration of error:
If I highlight the title of this question, the following alert box appears(I clicked the strikethrough option). Notice that the title has disappeared from the page.
node.innerHTML = node.innerHTML + message.paste
. Putting all messages in the same node. – Anthropomorphous