Create a bookmarklet that triggers a function to download files

I am interested in developing a bookmarklet that is capable of downloading a remote javascript file containing a defined function, and then executing that function with predetermined parameters.

Below is a typical "download-and-run-remote-script" bookmarklet, but with an additional function call included:

javascript:( function () { 
    var new_script = document.createElement("script"); 
    new_script.src = "http://mydomain.com/myscript.js"; 
    document.body.appendChild(new_script);
    do_stuff('Hello World!');
} ) ();

The code inside myscript.js consists of the following function:

function do_stuff(input_variable) {
    alert(input_variable);
}

Currently, this script does not provide the expected outcome. Why is that so? What modifications should be made to make it work as intended?

Answer №1

One benefit of scripts loading asynchronously is that they don't need to finish loading before you attempt to execute the function.

To address this issue, there are two potential solutions available:

Solution 1: Embed myvar = 'Hello World!' in a bookmarklet and then call do_stuff(myvar) in myscript.js

Solution 2: Implement the onload event for the script element you generate. This approach offers enhanced reliability but also comes with increased complexity.

Answer №2

The code below is fully functional on IE 10.0,9, Firefox 28, and Chrome 35.0.1916.114:

javascript:(function () {
    new_script = document.createElement("script");
    new_script.setAttribute('src','http://www.mydomain.com/myscript.js');
    if(new_script.addEventListener) {
        new_script.addEventListener("load", function() { do_stuff('Hello World!'); }, false);
    }else if(new_script.readyState) {
        new_script.onreadystatechange = function() { do_stuff('Hello World!'); };
    }else {
        new_script.onload = function() { do_stuff('Hello World!'); };
    }
    document.body.appendChild(new_script);
})();

I incorporated the first two "if" blocks based on recommendations found at this source: http://msdn.microsoft.com/en-us/library/ie/hh180173%28v=vs.85%29.aspx. However, Firefox required the final block to work smoothly. It's important to note that "do_stuff" should be enclosed in an anonymous function for compatibility with IE. I haven't yet verified its functionality on Opera and Safari. For a more detailed explanation of DG's response, check out this valuable resource shared by Matthew Lock: .

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to locate the URL for a node.js express website hosted on a VPS?

Recently, I acquired a VPS from OVH to host my discord bot. The VPS comes with a stats.json page that I need to be accessed by another website using a GET request. However, I am unable to locate the express site for my VPS. I have been trying to access it ...

Retrieve the content of the 'div' element, but exclude certain text

I have a task to copy the content from a div into a textarea, allow for editing within the textarea, and ensure that any changes made are saved back to the original div. I also need to filter out an attribute, such as data-bind: "some stuff;", set for the ...

Tips for animating a nested array using jQuery

I have a border that is 9x9 with lines, columns, and squares, similar to a Sudoku border. I want to animate it, but I encountered some issues when trying to run multiple animations simultaneously. To solve this problem, I decided to animate one array of el ...

Is there a method similar to insertBefore that works with arrays and/or HTMLCollections?

Is there a vanilla JavaScript or jQuery function that works like Node.insertBefore(), but for arrays and/or HTMLCollections? An example of what I'm looking for: var list = document.getElementsByClassName("stuff"); var nodeToMove = list[0]; var other ...

Encountering a build error in Next.js 13 when attempting to fetch an API route within a server component

I encountered an issue while building my next app (yarn run build). To troubleshoot, I created a new clean project and tested it. The problem seems to be with my route (/api/categories/route.ts) export async function GET() { return new Response(JSON.str ...

Utilizing jQuery to seamlessly animate decimal values

Currently facing a challenge while trying to animate a number from 0 to 36.6. The issue is that the end value gets rounded up to 37 instead of displaying as 36.6, which you can observe in this fiddle: http://jsfiddle.net/neal_fletcher/0f3hxej8/ Required ...

What is the process for combining two distinct geometries with different materials into a single entity in three.js?

I created a 2D square line diagram followed by another square diagram with a sample image in the center position. However, one of them is visible while the other is hidden. I used two different geometries and materials - one with a line-based material se ...

In JavaScript, the function will return a different object if the string in an array matches the

My task involves working with a simple array of string ids and objects. Upon initial load, I am matching these Ids with the objects and setting the checked property to true. const Ids = ['743156', '743157'] [ { "id&quo ...

The registration link for Google on my website is experiencing an error, while it works fine on the Allauth page

I am using the allauth module to authenticate users with Google. In the template /accounts/login/ provided by allauth, there is a link "google" that directs to href="/accounts/google/login/?process=login". Clicking on this link will authenticate the user ...

Renaming form elements using JQuery's .load method

This is a page named A.html <form name=form> <input type=text id = txtA> </form> When I use jQuery to load it into B.html, it loads multiple times. <form name=form> <input type=text id = txtA> </form> <form name=f ...

Validate that the input is an array

Looking for a way to determine if a function parameter is an array or not, and then process it accordingly. If the parameter is not an array, convert it into an array before performing the desired function. For example: interface employee { first: st ...

Using Angular select asynchronously within a custom directive

Despite my efforts, I am struggling to get an angular select with async to work properly. It seems to be mostly working, but not entirely. Consider the controller below: $scope.stuff = {}; $scope.stuff.blah = "SOME_KEY"; External.list().then( function ...

Restrict the movement of an object in Three.js to stay on the surface of another

My goal is to be able to drag an object and have it snap to the surface of another. Whether it snaps upon release or updates live doesn't matter to me. The ultimate objective is to create a smooth shape in Blender, import it, and enable snapping whil ...

Here's a way to programmatically append the same icon to multiple li elements generated using document.createElement:

I am new to creating a to-do app and need some guidance. When a user enters a task, I successfully create a list item for that task. However, I am unsure how to add a delete icon next to the newly created li element. Can someone please help me out? Below ...

Using jQuery, input data into a textarea element

I need assistance in extracting text from an element and inserting additional attributes to the text. The modified text should then be displayed in another element when a button is clicked. In my code snippet, the console.log() method correctly logs the d ...

The correct conclusion is reached by the function when the console.log statement is placed above the function call

By moving the console.log above the function call, the correct conclusion is reached. I double-checked multiple times by toggling the console.log on and off. Running on node.js v16.4.2. The input data is accurate. I attempted to replicate the issue in a di ...

Unlocking, accessing and manipulating images stored locally using JavaScript, p5.js, and HTML

Being faced with the challenge of displaying an image file from a local folder using JavaScript (p5.js), I am continuously encountering the following error message: Access to image at "XXXXX" from origin "null" has been block by CORS policy: The response i ...

Vue Pinia ensures that reactive state is only updated once, preventing unnecessary updates

In my Vue application, the structure is as follows: App.vue -GroupWrapper --GroupListing -PeopleWrapper --PeopleListing -ConversationWrapper Within my user store that utilizes Pinia, I primarily call user.findChats() in the App.vue component. Code snippe ...

Customize cell options in a dynamic grid within a dojo environment

When I double click on a cell in a data grid, I want to display a dropdown with information from a dojo store. However, the code I am using is not working as intended. I need to show clinician IDs stored in "clinStore" in the 'clinicianId' field ...

Pause until the array is populated before displaying the components

Currently, I am using firebase storage to fetch a list of directories. Once this fetching process is complete, I want to return a list of Project components that will be rendered with the retrieved directory names. How can I wait for the fetching to finish ...