Use a custom module to add JS to every page in Drupal 8
Assume the custom module is called example.

First create a example.libraries.yml file in your module root folder like this:

example:
  version: 1
  js:
    example.js: {}
  dependencies:
      - core/jquery


Next in example.module use hook_page_attachments() too add your JS to every page:

/**
 * Implements hook_page_attachments().
 */
function example_page_attachments(array &amp;$attachments) {
  $attachments['#attached']['library'][] = 'example/example';
}


So now the custom module has 4 files:


example.module
example.info.yml
example.js
example.libraries.yml


hook_page_build() and hook_page_alter() are now deprecated so can no longer use them.

There is a page drupal.org on adding CSS and JS using a custom module with more information.