execCommand("insertHTML", ...) in Internet Explorer - javascript

I'm building a wysiwyg-editor with an editable iframe using document.execCommand(). Now i need to use the "insertHTML" command which works perfectly in Chrome and Firefox but of course it doesn't work in Internet Explorer:
function run() {
document.getElementById("target").focus();
document.execCommand("insertHTML", false, "<b>ins</b>");
}
<div contenteditable id="target">contenteditable</div>
<button onclick="run()">contenteditable.focus() + document.execCommand("insertHTML", false, "<b>ins</b>")</button>
What is the standard solution to this problem? It's okay if it only works in IE8 but IE7-support would be nice too.

In IE <= 10 you can use the pasteHTML method of the TextRange representing the selection:
var doc = document.getElementById("your_iframe").contentWindow.document;
if (doc.selection && doc.selection.createRange) {
var range = doc.selection.createRange();
if (range.pasteHTML) {
range.pasteHTML("<b>Some bold text</b>");
}
}
UPDATE
In IE 11, document.selection is gone and insertHTML is still not supported, so you'll need something like the following:
https://stackoverflow.com/a/6691294/96100

In case you haven't found anything yet,
I had a button that would add html into an iframe, and was causing an error in IE8 when I clicked the button and no text was selected (i.e. when I had the blinking caret). It turned out that the button itself was getting selected (despite having unselectable="on"), and causing javascript to throw up the error. When I changed the button to a div (with unselectable on) it worked fine, in IE8 and FF.
Hope this helps.

I know this is extremely old, but since IE is still a problem, here is a better way which does not even use execCommand.
This is missing some checks, like ensuring you're in the right container to be adding an image.
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var frag = document.createDocumentFragment();
var img = document.createElement("img");
// add image properties here
frag.appendChild(img);
range.insertNode(frag);

var doc = document.getElementById("your_iframe").contentWindow.document;
// IE <= 10
if (document.selection){
var range = doc.selection.createRange();
range.pasteHTML("<b>Some bold text</b>");
// IE 11 && Firefox, Opera .....
}else if(document.getSelection){
var range = doc.getSelection().getRangeAt(0);
var nnode = doc.createElement("b");
range.surroundContents(nnode);
nnode.innerHTML = "Some bold text";
};

Related

Cursor position/index on textarea onClick event in IE11

Scenario : User makes onClick on a textarea(somewhere between the content without selecting any character just a click). Using javascript need to find the position of the cursor.
We had following script :
comp.focus();
var range = document.selection.createRange();
range.text='|';
var oldval = comp.value;
var pos= oldval.index('|');
Code was running with IE <11. With IE 11 ''dcoument.selection' was undefined. Then document says with IE11 "document.selection" should be "document.getSelection". Hence tried the following :
comp.focus();
var range = document.getSelection().createRange();
WIth ver11 , "document.getSelection().createRange()" says errors : Object doesnt support the propery or mehtod 'createRange()'.
Then tried to get object of 'var sel = document.getSelection()'. When i try to print as alert 'sel' , it says 'cannot get property toString on undefiend or null references'
1. With older version document.selection.createRange worked well even if there isnt any character seelcted/highlighted. But with IE11 its not as such.
2. Please let me know how to createRange evne if there isnt any selected characters.
Need solution/suggestion to proceed.......
I use this function to get cursor position:
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
The following code returns cursor position:
comp.getCursorPosition();
works fine with IE11

How I can access the selected text in IE11 from context menu, and copy to Clipboard

I have tried anything to get the selected text for a context menu, but it is not working in IE11.
For context menu adding I have added some code in registry, and a htm file with a Javascript.
First I have tried this:
var parentwin = external.menuArguments;
var doc = parentwin.document;
var sel = doc.selection;
var rng = sel.createRange();
var selectedtext = new String(rng.text);
then I have read in IE11 documentation, the document.selection has been repalced in the API with window.getSelection();
So I have tried any variant, window.getSelection... nothing works...
Any idea how I can access the selected text?
And I have searching also how I can copy to the clipboard.. in chrome I have used this script:
function copyToClipboard(text){
var copyDiv = document.createElement('div');
copyDiv.contentEditable = true;
document.body.appendChild(copyDiv);
copyDiv.innerHTML = text;
copyDiv.unselectable = "off";
copyDiv.focus();
document.execCommand('SelectAll');
document.execCommand("Copy", false, null);
document.body.removeChild(copyDiv);
}
Finally I have found the solution: (tested in IE11)
var parentwin = external.menuArguments
var selectedText = getSel();
function getSel(){
var w=window,d=parentwin.document,gS='getSelection';
return (''+(w[gS]?w[gS]():d[gS]?d[gS]():d.selection.createRange().text)).replace(/(^\s+|\s+$)/g,'');
}
parentwin.console.log("the selected text is:"+sel);
copyToClipboard(selectedText);
function copyToClipboard(s) { //only works in IE :(
if (window.clipboardData && clipboardData.setData) {
clipboardData.setData('text', s);
}
}

how set style display in opera?

I have this html code for my button:
Click
and this javascript code for set display style the button:
function setstyleint()
{
var divArray = document.getElementById('processLink');
divArray.style.display = 'initial';
}
it work in ff and chrome very good.
but in opera and ie(my version is 9) do not work,
is there any help?
best regards.
Try divArray.style.display = '';
insted of divArray.style.display = 'initial';
also commented by epascarello

Ckeditor selected html not working correct with chrome browser

Iam working in an mvc application and using ckeditor 3.6.2 version. I have used the following code for getting selected html from ckeditor.
CKEDITOR.editor.prototype.getSelectedHtml = function () {
if (CKEDITOR.env.ie) {
this.focus();
selection = this.getSelection();
} else {
selection = this.getSelection();
}
if (selection) {
var bookmarks = selection.createBookmarks(),
range = selection.getRanges()[0],
fragment = range.clone().cloneContents();
selection.selectBookmarks(bookmarks);
var retval = "",
childList = fragment.getChildren(),
childCount = childList.count();
for (var i = 0; i < childCount; i++) {
var child = childList.getItem(i);
console.log(child);
retval += (child.getOuterHtml ?
child.getOuterHtml() : child.getText());
}
return retval;
}
};
I have an issue in chrome browser when I selected a text and call CKEDITOR.instances.editor1.getSelectedHtml().
For example, suppose in my editor there is a content <span style="color:red;">Welcome Note</span>. If I selected "Welcome Note" and call getSelectedHtml() method firefox,safari,IE8 returns "Welcome Note" with span tag, but chrome returns only the text "Welcome Note". If Iam trying to replace the selected content using CKEDITOR.instances.editor1.insertHtml("<div style='font-size:12px'>"+ CKEDITOR.instances.editor1.getSelectedHtml()+"</div>"), in chrome I lost the font color since getSelectedHtml() returns only the selected text. But this works fine with other browsers.
Note : If the content is "Welcome <span
style="color:red;">Note</span>" and the selected word is "Welcome
Note". In this case,this will be correct in chrome and other browsers.
Please suggest a proper solution.
There have been some similar cases that are documented on the CKEDITOR web site. In particular, take a look at this one:
http://cksource.com/forums/viewtopic.php?f=11&t=20202

Focus textarea with caret after text in Android browser

I am currently writing a simple webapp to view tweets in the Android browser.
I am using this code to focus the caret after the current text:
var oldContent = document.tweetBox.tweet.value;
document.tweetBox.tweet.value = '';
document.tweetBox.tweet.focus();
document.tweetBox.tweet.value = oldContent + to;
This code works flawlessly in Chrome, Fluid, Opera, Firefox en Safari.
The weirdest part is that the cursor starts blinking AFTER the 'to' text if I use my hardware keyboard but the text that I enter starts where I was typing before the JS above was executed.
If I use the soft keyboard the text entering starts at the start of the textarea.
p.s The javascript is part of a suggestion for followers, so if you start typing #gn it will suggest #gnur_nl in a seperate div and when you press enter this entry is chosen.
Update: This behaviour seems to be the result of a browser bug, a bug report has been filed.
Sounds like a browser bug. Try setting the caret position manually:
var textArea = document.tweetBox.tweet, oldContent = textArea.value;
textArea.value = oldContent + to;
textArea.focus();
textArea.selectionStart = textArea.selectionEnd = textArea.value.length;
setCaret = function(obj,pos) {
// IE Support
if (document.selection) {
// Set focus on the element
obj.focus ();
// Create empty selection range
var oSel = document.selection.createRange ();
// Move selection start and end to 0 position
oSel.moveStart ('character', -obj.value.length);
// Move selection start and end to desired position
oSel.moveStart ('character', pos);
}
//standard browsers
else if (obj.selectionStart || obj.selectionStart == '0') {
obj.selectionStart = pos;
obj.selectionEnd = pos;
obj.focus ();
}
};
and setting to the right positions
setCaret(document.getElementById("area"),document.getElementById("area").value.length);

Categories

Resources