Score:0

How do I make JavaScript behavior run on every page load?

th flag
fin

I don't know how to run my Drupal.behaviours.mybehaviour on every page load.

Here's my code example that run only once, when I load the page is no longer run my code, how can I change that from once to run on every page load:

       Drupal.behaviors.searchFilter = {
            attach: function (context) {
               once('searchFilter', 'html', context).forEach( function () {
                   console.log("function run");
               });
            }
       }
Jaypan avatar
de flag
Drupal.behaviors is already run on every page load, so it's not clear what you mean.
fin avatar
th flag
fin
For example: How can I run console.log("test loading page") display on every page load.
Jaypan avatar
de flag
`Drupal.behaviors.searchFilter = { attach: function (context) {console.log("test loading page");}};`
fin avatar
th flag
fin
@Jaypan thanks for that, how can I attach my library so it get called on every page load. Right now I attached inside my custom module on a checkbox element, but it only execute when the form is submit.
Jaypan avatar
de flag
`Drupal.beviours` is already called on every page load. So I don't know how to answer your question.
fin avatar
th flag
fin
thanks @Jaypan - I'm investigate further, could be a cache issue. thanks :)
Score:0
th flag
fin

I found, you have to attach your library using the hook_page_attachments This hook will attach your library on every page, so it will run on page load.

Then you can execute your js script like the following:

 Drupal.behaviors.searchFilter = {
            attach: function (context) {
                console.log("function run");
            }
       }
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.