Skip to main content

How to allow SMS links in Drupal

Back-end Development
Drupal

With mobile web use on the rise, the chance of your site's visitors being on a cell phone are ever increasing. To make it easy to contact you, you may want to add a link to your site to allow your users to send you a text. Perhaps you wrote part of a render array that looks like this:

$build['sms'] = [
  '#type' => 'link',
  '#title' => t('Send us a text!'),
  '#url' => Url::fromUri('sms:1234567890'),
];

But there's one problem with this: Drupal will give you an exception!

InvalidArgumentException: The URI 'sms:' is invalid. You must use a valid URI scheme. Use base: for a path, e.g., to a Drupal file that needs the base path. Do not use this for internal paths controlled by Drupal. in Drupal\Core\Utility\UnroutedUrlAssembler->assemble() (line 65 of core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php).

This is for a good reason. Drupal filters any links it outputs so that malicious HTTP schemas can't be embedded in your site. The list of allowed schemas can be found in your sites/default/services.yml file under filter_protocols. This is the default list:

filter_protocols:
  - http
  - https
  - ftp
  - news
  - nntp
  - tel
  - telnet
  - mailto
  - irc
  - ssh
  - sftp
  - webcal
  - rtsp

To allow SMS links, simply add an "sms" entry at the end of this list.

Need a fresh perspective on a tough project?

Let’s talk about how RDG can help.

Contact Us