Detect if browser supports contentEditable?

2019-03-29 19:52发布

问题:

There's this question, but the solution posted is browser sniffing, which I'm trying to avoid.

I need to make my website compatible with the iPad and perhaps newer Androids. I've been using an old version of the FCKEditor (now CK Editor) for my WYSIWYG editors, but that doesn't work on mobile, so I want to swap it out for a simple textarea with something like markdown, if it's not supported.

Supposedly it won't work because mobile devices tend not to support this contentEditable property, which means the on-screen keyboard won't pop up when you click on it.

How can I detect if the browser supports contentEditable? It's been suggested that I just check the div in question with something like mydiv.contentElement === undefined or something like that, but the div (if it's using one) is all built into the FCK Editor and buried somewhere in an iframe.

Isn't there another way to detect if a browser supports contentEditable in general?


Just tried this:

var contentEditableSupport = typeof $('<div contenteditable="true">')[0].contentEditable !== 'undefined';

Says "true" on my iPad...... I don't think it should.

Edit: It's returning "string" because all attributes are strings.... it's just reading the attribute. How else am I supposed to do this?

回答1:

Here is the test I use and is also used in Modernizr. It will give false positives in iOS 4 (and possibly earlier) but unfortunately it's impossible to detect in those environments.

var contentEditableSupport = "contentEditable" in document.documentElement;


回答2:

You could create an anonymous editable div, check it for contentEditable, then remove the div.



回答3:

I was able to accomplish this by checking the default value of the contentEditable property rather than the presence or type. The W3 spec indicates that the missing value default for contentEditable is "inherit", but in older browsers (e.g. Android/Gingerbread) the default value is "false". Thanks to fudgey for the comment on the OP that pointed me in the right direction!

This test works for me:

var contentEditableSupport = $('<div/>')[0].contentEditable == 'inherit';


回答4:

Check for execCommand

if (document.execCommand) {
    ... browser supports contentEditable
} else {
    ... browser doesn't support contentEditable    
}


回答5:

To check if any propery exits for a element. You can do this

var element = document.createElement('__ELEMENT__');
if ('__PROPERTY__' in element ) {
    // property supported in the browser
}

or

if ('__PROPERTY__' in document.createElement('__ELEMENT__') ) {
    // property supported in the browser
}

The below link contains it all.

  1. https://github.com/Modernizr/Modernizr/issues/570
  2. http://diveintohtml5.info/everything.html#contenteditable