Detect if browser supports contentEditable?

2019-03-29 19:54发布

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?

5条回答
不美不萌又怎样
2楼-- · 2019-03-29 20:19

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

查看更多
相关推荐>>
3楼-- · 2019-03-29 20:20

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
查看更多
放荡不羁爱自由
4楼-- · 2019-03-29 20:24

Check for execCommand

if (document.execCommand) {
    ... browser supports contentEditable
} else {
    ... browser doesn't support contentEditable    
}
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-03-29 20:33

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';
查看更多
Evening l夕情丶
6楼-- · 2019-03-29 20:43

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;
查看更多
登录 后发表回答