Embedding script into the webpage is ineffective

After posting a query yesterday, I found myself in need of further clarification.

I've been working on a userscript designed for Chrome (similar to GreaseMonkey). The main goal is to insert a textbox and a button onto the page. When the user clicks the button, it should trigger a function. However, despite successfully injecting the necessary components and functions, an error message pops up in the Chrome console stating "Uncaught TypeError: object is not a function." It seems that the function specified in the onclick event for the button is not being recognized.

The code snippet looks something like this:

initialize();

function initialize() { 
    var dropDown = document.getElementById("tstGlobalNavigation_ddlChooseProject"); 

    // add a textbox 
    dropDown.innerHTML = dropDown.innerHTML + "&nbsp;&nbsp;&nbsp;<input type='text' name='txtSearch' style='position:absolute;top:8px;left:800px;width:50px' >";

    // add a button 
    dropDown.innerHTML = dropDown.innerHTML + "&nbsp;&nbsp;&nbsp;<input type='button' name='btnSearch' value='Go' onclick='fn()' style='position:absolute;top:8px;left:860px;width:35px'>";

    addScript("var obj = document.getElementById('txtSearch'); " 
    + "if (obj != null) { " 
    + " var incidentId = document.getElementById('txtSearch').value; " 
    + " var currentURL = location.href; " 
    + " var splitResult = currentURL.split('/'); " 
    + " var projectId = splitResult[4]; " 
    + " location.href = 'http://dev.myApp.com/ProductTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; " 
    + " }" 
    , "fn"); 
}

function addScript(contents, id) { 
    var head, script; 
    head = document.getElementsByTagName('head')[0]; 
    script = document.getElementById(id); 
    if(script != undefined) { 
    head.removeChild(script); 
    } 
    script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.id = id; 
    script.innerHTML = contents; 
    head.appendChild(script); 
}

It appears that there might be some crucial oversight on my part. What aspect am I neglecting?

Answer â„–1

Instead of referencing the function you created, make sure to actually call it by using the assigned id in the script tag... To fix this issue, update the code like so:

addScript("function fn() { var obj = document.getElementById('txtSearch'); " 
    + "if (obj != null) { " 
    + " var incidentId = document.getElementById('txtSearch').value; " 
    + " var currentURL = location.href; " 
    + " var splitResult = currentURL.split('/'); " 
    + " var projectId = splitResult[4]; " 
    + " location.href = 'http://dev.myApp.com/ProductTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; " 
    + " } }" 
    , "fn"); 

By making these changes, you will now have a functional fn() that can be executed.

Answer â„–2

The issue arises when attempting to utilize the onclick element attribute to attach an event handler. These attributes are only processed upon initial page load, during which the function intended for binding as the callback is non-existent.

It is advisable to refrain from attaching event handlers in element on* attributes whenever feasible. This practice aligns with the principles of composing unobtrusive JavaScript.

Nevertheless, if there is an absolute need to persist with using onclick, a workaround could involve linking to a placeholder function that simply triggers the injectioned function:

<button onclick="wrapper()"

In this scenario, wrapper may resemble the following structure:

function wrapper() {
    return functionThatWillEventuallyBeInjected();
}

Answer â„–3

It may not be possible to dynamically create script tags and insert content into them.

An alternative approach would be to create a script tag and change the src attribute to point to a JavaScript file:


var myScript = document.createElement("script");
myScript.type = "text/javascript";
myScript.src = "path/to/your/script.js";
document.body.appendChild(myScript);

If you really must run code from a string, you could consider using the eval() function when necessary!

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

Can VueJS support multiple v-slots in a component?

I recently set up vee-validate v3.0 for validation in my project and everything was going smoothly until I tried to style my elements. Despite following the documentation on styling and making changes to the vee-validate config, I encountered a new issue - ...

Transforming a form submission into an AJAX post while already in an AJAX post

I am looking to convert a form submission to an ajax post request while working within the codeigniter framework. The current JavaScript code is: $('#book-appointment-submit').click(function(event) { event.preventDefault(); var formData ...

JavaScript method overloading involves defining multiple functions with the same name

In my JavaScript code, I have implemented method overloading using the following approach: function somefunction() { //1st function } function somefunction(a) { //2nd function } function somefunction(a,b) { //3rd function } somefunction(); // ...

Express, the mongoose package delivers a response of an empty array

I have encountered a common issue regarding pluralization with mongoose default model names. Despite trying various solutions, the problem persists as I am getting an empty array as the result. In my local mongoDB database, there are 2 documents in the "us ...

Tips for effectively passing state from a parent component to a child component without losing it

I created a view displaying all posts with a filter above them. Users can customize their view by selecting different options on the filter, resulting in updated posts being shown. However, if a user clicks on a post after applying filters, the parent com ...

Is there a way to stop ng-repeat in AngularJS 1.2 from encoding or escaping my content, or do I have to create my own directive for this?

Is there a way to stop ng-repeat in AngularJS 1.2 from encoding or escaping my content without creating a custom directive? I know that ng-bind-html-unsafe is no longer supported in Angular 1.2, but I'm unsure about its compatibility with ng-repeat. S ...

The id property of undefined cannot be accessed in the discord.js library

I am currently developing a Discord bot that assigns a role temporarily whenever a specific word is mentioned. Despite thoroughly checking my code, I continue to encounter the following error: message.member.roles.add(role555.id); ...

Connecting a Kendo Dropdown menu to external data sources for seamless integration

I need help with binding data to a dropdown list for my local service. Whenever I try to download the data, I keep getting an error message: Uncaught SyntaxError: Unexpected token: Does anyone have any ideas on how to resolve this issue? This is my JS ...

Ways to obtain the coordinates that surround a particular x, y location

I am trying to figure out how to generate an array of coordinates around a specific x, y point. For instance: xxxxx xxoxx xxxxx In this case, "o" is located at coordinates 3, 2. Now I aim to produce: xxx xox xxx as the set of coordinates surrounding "o ...

Experience the seamless transition of new CSS animations

I designed a basic HTML game where a moving box disappears when clicked on. However, the animation that follows does not originate from the click location but rather from the original position. I believe the remove @keyframes at 0% should be based on the ...

Encountering an unexpected identifier error in Sails JS

As a newcomer to Sails JS, I am attempting to perform CRUD operations with it. However, I am encountering an unexpected error in my index function. I am struggling to identify where the mistake lies. // Usercontroller.js file module.exports = { creat ...

Miscalculation occurred when attempting to add or subtract values from various inputs

My goal is to calculate the sum and rest of two different values after adding or subtracting. For instance, I have a Total variable = 500, along with two input fields - one for MXN and the other for USD. Additionally, there is a USD variable set at 17.5. T ...

What is the best way to extract the ID from an event in TypeScript?

HTML Code: <ion-checkbox color="dark" checked="false" id="1on" (ionChange)="onTap($event)" ></ion-checkbox> TypeScript Code: onTap(e) { console.log(e); console.log(e.checked); } I am trying to retrieve the id of the checkbox. H ...

No change in the element's text content when clicking

I'm working on creating a timer that counts down from either 15 or 30 seconds. However, I'm having trouble changing the text value when the 15 button is clicked. Can someone help me figure out what's wrong? Thank you in advance HTML <h ...

Adjust top position dynamically during resizing

When resizing the window, I am facing an issue with the image going outside of the box. I believe adjusting the position top of the image based on the box height might help in fitting the image properly within the box. $(window).resize(function() { va ...

Struggling to correctly showcase my Firebase data in Angular using the orderByChild method

I have a user database structured like this : Database - Users - Id (generated using the push method) - email - firstName - ptsTotal - ... I am looking to create a ranking of users based on their total points (ptsTotal) in a game using ...

What is the best way to update the color of a label in a Mantine component?

When using the Mantine library, defining a checkbox is done like this: <Checkbox value="react" label="React"/> While it's possible to change the color of the checkbox itself, figuring out how to change the color of the label ...

Tips for importing modules for unit tests using QUnit

Lately, I've been working on implementing unit tests for some of my modular ES6 code. The project structure I have looks something like this: project └───src | └───js | cumsum.js | index.js <--- main file └─┠...

Creating a Breeze js entity using a JSON string and importing it into the breeze cache: A step-by-step guide

Currently, I am developing a mobile single page website that utilizes technologies like breeze js, angular js, web API, and entity framework. To enhance the performance of the site, I have decided to include the breeze metadata in a bundled JavaScript fil ...

Create a dynamic select2 field based on the value selected in another dropdown menu

Starting with an initial dropdown where a value needs to be selected: <select id="indexID" name="indexID" class="form-control" onChange="updateSector();" style="width:300px;"> <option value='' selected>Choose an Index</option> ...