Skip to main content

Insert JavaScript and CSS code to APEX from PL/SQL

O

One of my colleagues (lets name him Max) prepared a surprise for me. I had no idea where is the JavaScript code being placed on page. Turned out, there is an API for injecting JavaScript code from PL/SQL and you can do the same with CSS. That is not just an excellent hiding place, but it can be used if you need to attach these on page dynamically.

Checkout the APEX_JAVASCRIPT api, especially the ADD_ONLOAD_CODE procedure.


For example you can set the JavaScript variable from the PL/SQL.

BEGIN
    APEX_JAVASCRIPT.ADD_ONLOAD_CODE (
        p_code => 'variable_name = new_value;'
    );
END;
/

Better version would be to escape the value using ADD_VALUE (which is an equivalent of APEX_EXEC.ENQUOTE_LITERAL but for JavaScript) or APEX_JAVASCRIPT.ESCAPE function:

BEGIN
    APEX_JAVASCRIPT.ADD_ONLOAD_CODE (
        p_code => 'variable_name = ' || APEX_JAVASCRIPT.ADD_VALUE('new_value', p_add_comma => FALSE) || ';'
    );
END;
/


Similar thing can be achieved with CSS. You can inject specific styles using APEX_CSS.ADD or the whole file with APEX_CSS.ADD_FILE:

BEGIN
    APEX_CSS.ADD (
        p_css => '.CSS_CLASS_NAME { border: 1px solid #f00; }'  -- thats how old I am :-)
    );
END;
/

I see a nice usecase for this. I have the CSS region on page zero, which is a dynamic content region, and I generate CSS classes there. With this, I could move it to the init process and keep global page clean.

Or you can do this just to suprise your colleagues :-)


And for those who noticed I was not around in past 2 months, I was busy at work, working on my personal apps, travelling and preparing abstract and presentation for the APEX Alpe Adria conference. The goal is to post article at least twice a month now.

Thank you for your support and keep learning.


Comments