简体   繁体   中英

Call a function in Javascript file from tampermonkey script

I'm trying to write a tampermonkey script and want to call a javascript function which is provided by the webpage. The HTML of the page looks like this:

<ui-button class="action-button-spacing" id="downloadAs" variant="normal" text="Download as" click="openDownloadAsPanel()" data-disabled="actionButtonsDisabled()" initialized="true"><button class="ui-button ui-button-size-normal ui-button-variant-normal ui-hover-child-icons" type="submit"><span region-container="text">Download as</span></button></ui-button>

My script creates a button on the page, and I want it to call the openDownloadAsPanel method, whose definition is in a JS file (not part of the HTML file).

For this I tried this:

function addFunction(func, exec) {
    var script = document.createElement("script");
    script.textContent = "-" + func + (exec ? "()" : "");
    document.body.appendChild(script);
    document.body.removeChild(script); // clean up
}

function myFunction () {
    return openDownloadAsPanel();
}

And then onclick of the button created by me, addFunction(myFunction, true); I get an error: openDownloadAsPanel is not defined

Also I don't know the file of the javascript file as it is served by cloudfront and the name keeps changing if the file changes. Or probably I will have to parse all the javascript file name/path written in the HTML file.

I don't think you can call a function that is ran by the webpage. Your best bet would probably be trying to see what the code in the function is and defining your own function with that same code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM