Search code examples
javascriptgreasemonkeyuserscriptstampermonkey

Usercript access to Dynamically generated (Vaadin framework) content


I'd like to get access in javascript to DOM elements generated by Vaadin bootstrap. Let's say page: https://vaadin.com.

If you check the website content in Chrome > inspect element everything seems fine. We can navigate between html elements and everything is fine. But the content won't be displayed in Chrome > view page source.

Anyway, if we run a script like this in Tampermonkey:

// ==UserScript==
// @name         TEST
// @namespace    http://tampermonkey.net/ 
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://vaadin.com/
// @requirehttp://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require      https://gist.github.com/raw/2625891/waitForKeyElements.js
// ==/UserScript==

console.log($('.front-page-view'));

$(document).ready(function () {
    console.log($('.front-page-view').html());
});

or even in "console" command (if page with above script is loaded) like:

$('.front-page-view').html();

every time we got

undefined

How do we get the userscript to see this code?


Solution

  • Closely related to: Fire Greasemonkey script on AJAX request.

    The userscript fires long before the .front-page-view node(s) is/are loaded. So, the existing code sees nothing.

    Here's how to waitForKeyElements to compensate for that (complete working script):

    // ==UserScript==
    // @name        Vaadin.com, show code of dynamic element
    // @match       https://vaadin.com/*
    // @require     https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
    // @require     https://gist.github.com/raw/2625891/waitForKeyElements.js
    // @grant       GM_addStyle
    // @grant       GM.getValue
    // ==/UserScript==
    //- The @grant directives are needed to restore the proper sandbox.
    
    waitForKeyElements (".front-page-view", showNodeHTML);
    
    function showNodeHTML (jNode) {
        console.log ("FPV html: ", jNode.html().trim() );
    }
    

    Pay close attention to the metadata block as the question code has errors there.