Search code examples
wordpresswordpress-plugin-creation

Writing bookmarklet to reveal accordions


My JavaScript code:

javascript:(function(){ 
    function makeRed(){
        document.body.style.backgroundColor = "red";
    }


    function makeWhite(){
        document.body.style.backgroundColor = "white";
    }


    makeRed();
    setTimeout(makeWhite, 1000);

    var elements = document.querySelectorAll(".unbox[unbox=\"extra_examples\"]")

    for (const elem of elements) {
      elem.classList.add("is-active");
    }

})();

The JavaScript code works (reveals Extra examples at Oxford Learners Dictionary) and signals about that by blinking.

I would like to create a plugin for WordPress that adds a shortcode for a bookmarlet.

This is an example of a bookmarklet:

<a href="javascript:void%20function(){var%20a=prompt(%22What%20is%20your%20name%3F%22,%22Your%20Name%22);null!=a%26%26alert(%22Hello%20%22+a)}();">
My bookmarklet
</a>

My PHP:

<?php

/**
 * Plugin Name:       N-bookmarklet
 * Description:       Bookmarkets
 * Version:           0.1
 * Requires at least: 5.8.1
 * Requires PHP:      7.2
 * Author:            Nonverbis */


function oald() {
    
    // Reveals extra examples at OALD.
    
    $js =<<<END
function makeRed(){
    document.body.style.backgroundColor = "red";
}


function makeWhite(){
    document.body.style.backgroundColor = "white";
}

javascript:(function(){ 

    makeRed();
    setTimeout(makeWhite, 1000);

    var elements = document.querySelectorAll(".unbox[unbox=\"extra_examples\"]")

    for (const elem of elements) {
      elem.classList.add("is-active");
    }

})();
END;
   
    $html = '<a href="' . $js . '">Oxford Extra</a>';
    
    return $html;
}




add_shortcode( 'n-oald', 'oald' );

This code produces an error:

enter image description here

I seem to have failed to strip the code or something. I have tried to do that by hand, without using any libraries. But anyway, the error is still present.


Solution

  • You need to escape your JS code in the HTML tag with %. See here for an live example

    <a href="javascript:!function()%7Bdocument.body.style.backgroundColor%3D"red",setTimeout((function()%7Bdocument.body.style.backgroundColor%3D"white"%7D),1e3)%3Bvar o%3Ddocument.querySelectorAll(%27.unbox%5Bunbox%3D"extra_examples"%5D%27)%3Bfor(const e of o)e.classList.add("is-active")%7D()%3B">my bookmarklet</a>