Jump to content
DrQuincy

Disallow href="javascript:*" in CKEditor

Recommended Posts

I use CKeditor 4, the same as PW, in other projects and have noticed it allows <a href="javascript:alert(document.cookie)">.

Does anyone know how I can use config to disallow any hrefs that start with javascript:? It's fine in PW as HTML Purifier seems to catch it but I wondered for other projects. There is an option config.linkJavaScriptLinksAllowed but it only applies to the link dialog.

I'm sure it must be doable with regex in config.allowedContent but I'm drawing a blank.

Thanks.

Share this post


Link to post
Share on other sites

I don't think it's possible to use regex in config.allowedContent, but this seems to do the job:

CKEDITOR.on('instanceReady', function(event) {
	var rules = {
		elements: {
			a: function(element) {
				// If a link href starts with 'javascript:'...
				if(element.attributes.href.substring(0, 11).toLowerCase() === 'javascript:') {
					// ...then the href is invalid so remove the link
					delete element.name;
				}
			}
		}
	};
	event.editor.dataProcessor.htmlFilter.addRules(rules);
	event.editor.dataProcessor.dataFilter.addRules(rules);
});

 

  • Like 1

Share this post


Link to post
Share on other sites

Thanks, I'll give it a go when I am in the office later!

Do you think it is odd it allows this by default but disallows it in the link dialog? Is there a reason for it or is it an oversight?

Share this post


Link to post
Share on other sites

This is great. I have just added .trim() so that it picks up on href="   javascript:alert('');" too.

if (element.attributes.href.trim().substring(0, 11).toLowerCase() === 'javascript:') {

Thanks again. 🙂

  • Like 1

Share this post


Link to post
Share on other sites

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...