How to send arguments to an external JavaScript file with JavaScript

In the header of my HTML document, I have included the following script:

<script src="http://www.domain.com/js/widgets.js" type="text/javascript"></script>

This script references:

widgets.js

(function () {

    var styleEl = document.createElement("link");
    styleEl.type = "text/css";
    styleEl.href = "http://127.0.0.1:8002/static/css/widgets.css";
    styleEl.rel = "stylesheet";

    //document.getElementsByTagName('head')[0].appendChild(styleEl);
    document.head.appendChild(styleEl);

    document.write("<div id='share_box'>" +
        "<a href='test' target='_blank'>R</a>" +
        "</div>");
})();

I attempted to pass a variable into this external file by doing the following:

<script src="widgets.js" type="text/javascript">
     var url = 'https://www.domain.com/link/'
</script>

What is the best way to pass the URL variable to my external script securely using only vanilla JavaScript (no jquery)?

Answer №1

The URLs you've shared seem to be non-existent. There doesn't appear to be anything there, but here is the code snippet you are working with:

(function () {

    var styleEl = document.createElement("link");
    styleEl.type = "text/css";
    styleEl.href = "http://127.0.0.1:8002/static/css/widgets.css";
    styleEl.rel = "stylesheet";

    //document.getElementsByTagName('head')[0].appendChild(styleEl);
    document.head.appendChild(styleEl);

    document.write("<div id='share_box'>" +
        "<a href='test' target='_blank'>R</a>" +
        "</div>");
})();

Having Trouble Passing a Parameter (Illustrated in this Example)

In this scenario, it appears that passing a parameter is not feasible as the setup does not support it.

Procedure for Function Parameter Input

When wishing to incorporate a parameter into a function, the function must accommodate the parameter during its declaration. For instance:

function someFuncName (params) {
  /* At this moment, the parameters can be transmitted! */
}

The current script you're dealing with lacks the capability to accept parameters due to no provision being made for them.

Technique for Imposing a Parameter

If you wish to transmit a parameter, you typically utilize the following syntax:

<script>
  functionName(params);
</script>

It's a simple process, but unfortunately, it is not feasible in your present situation!

Overview of the Provided Code's Functions:

The functionality of the given code involves including a link element like so:

<link type="text/css" href="http://127.0.0.1:8002/static/css/widgets.css" 
rel="stylesheet" />

Furthermore, the code generates an HTML element structure as follows:

<div id="share_box">
  <a href="test" target="_blank">R</a>
</div>

This may potentially create a hyperlink and then stylize it using the provided .css file from the website mentioned in the href attribute.

Nonetheless, the key point remains: passing a parameter to an external file is only achievable if the file permits such interaction.

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

Updating JSON data using fetch API

Hi everyone, I'm currently working on an email application and need help with implementing an archive button for each email. It seems that the function to change the archived status to true is being called, but for some reason, it's not making th ...

Verifying user login on NodeJS through connection from an IIS-hosted website

I am currently upgrading an outdated CMS system and looking to implement a real-time chat feature. The existing CMS operates on IIS, MSSQL, and PHP. The chat feature will be hosted on a separate Linux box running Node.js and Socket.io After successfully ...

The callback function for the XMLHttpRequest object is not triggered when making a cross-domain request using jQuery/Ajax

Looking for some help with this code snippet I have: $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentCo ...

What could be causing an error in my Vue app when attempting to process a payment using Google Pay on a mobile device, resulting in the message "Blocked a frame with origin

When implementing payment through Google Pay on Chrome desktop, it functions smoothly. However, an error occurs when attempting to pay using a smartphone, triggering an additional modal window with a card selection: vue.esm.js?a026:152 Uncaught (in promise ...

Can you provide instructions on utilizing the async .update() function for DataTables within MDBootstrap?

I am just starting to explore MDBootstrap and I'm currently focused on grasping how to utilize the DataTables. While I've browsed through the examples on their website regarding Async table updates, I've found it a bit challenging to adapt i ...

What is a reliable method for automatically refreshing a webpage despite encountering server errors?

I'm working on an HTML+JS web page that refreshes itself automatically every few seconds using http-equiv="refresh". The problem is, sometimes the server returns a 502 "bad gateway" error, preventing the HTML code from loading and causing th ...

Creating Scroll Animations in Javascript - Mastering scrollIntoView Animation

When I click on a div, I was only able to bring it into view with the scrollIntoView function. It functions correctly and meets my expectations, but I am curious if there is a way to animate it and slow down the process. I attempted a suggestion found her ...

Jsx Component fails to display following conditional evaluations

One issue I am facing is having two separate redux stores: items (Items Store) quotationItems (Quote Items). Whenever a product item is added to quotationItems, I want to display <RedButton title="Remove" />. If the quotationItems store i ...

Removing Access Package Assignment in Microsoft Graph

Using the Microsoft Graph API Beta version, I am attempting to delete an access package. However, in order to do so, I must first remove all assignments associated with it. As per the official documentation, I came across the accessPackageAssignment object ...

Client-side filtering for numerical columns using the Kendo UI Grid widget

In my Kendo UI grid widget, I have a model schema set up for a field like this: RS_LookBackDays: { type: "number", editable: true }, The columns configuration for the same field looks like this: { field: "RS_LookBackDays", title: "Rate Schedule – # Lo ...

Troubleshooting a bug in React TypeScript with conditional logic

I have a new message button and a few conversations. When I click on a conversation, the right side should display the message box. Clicking on the new message button should show the create new message box. Here are my useState and handlers: const [newMess ...

What is the best method to make a hyperlink within an IFrame open in a new window?

Let me share the code I've been working on: <!DOCTYPE html> <html> <head> <base target="_blank"> </head> <body> <div style="border: 2px solid #D5CC5A; overflow: hidden; margin: 15px auto; max-width: 800px; ...

Sliding with jQuery to eliminate a div element

I wanted to dive into jQuery and decided to recreate the slick animation from Jay-Z's new album commercials. In these ads, a bar slides left over his name while simultaneously disappearing. I also wanted to add a flashing effect by fading out, fading ...

Switch the selected option in JQuery UI dropdown using a clickable button

I have a code snippet that is almost working. My goal is to change the selection of a JQuery dropdown select combobox using a separate button named "next". What I want is for the JQuery dropdown to automatically switch to the next selection every time I c ...

What is the purpose of using an open quote and bracket in the `eval('('+jsonString+')')` syntax for parsing a JSON string?

What is the rationale behind this particular syntax structure? eval('(' + jsonString+ ')') When it comes to parsing JSON text, Crockford explains that "The text must be wrapped in parentheses to prevent any confusion with JavaScript& ...

The Best Way to Display Quad Wireframe in Three.js using OBJ Model

I am trying to display the wireframe of OBJ meshes using Three.js. However, Three.js can only render triangles, so I came up with the idea of creating a line for each edge of the model. After parsing the OBJ file and iterating through its vertices and fac ...

Capturing the input value from a text box within a table cell, saving it in an array using Javascript, and then transmitting it back

I have a PHP-generated table displayed on my website. The table consists of two rows - the first row contains headers, and the second row contains text boxes inside each cell. My goal is to allow users to input values into these text boxes, then retrieve t ...

Create an XML file with recurring elements based on JSON data

Currently, I am utilizing the xmlBuilder library within Nodejs to generate XML from a prepared JSON object. My approach involves crafting the JSON structure first and then transforming it into XML using Javascript as the coding language. The specific XML ...

Simulating a PubSub publish functionality

I have been trying to follow the instructions provided in this guide on mocking new Function() with Jest to mock PubSub, but unfortunately I am facing some issues. jest.mock('@google-cloud/pubsub', () => jest.fn()) ... const topic = jest.fn( ...

Incorporating a dropdown menu into an HTML table through jQuery proves to be a

I loaded my tabular data from the server using ajax with json. I aimed to generate HTML table rows dynamically using jQuery, with each row containing elements like input type='text' and select dropdowns. While I could create textboxes in columns ...