What could be causing the issue with script.onload not functioning properly in a Chrome userscript?

I am trying to use a userscript to load another script file on a website. However, I am encountering issues with the js.onload event not working as expected.

Here is the userscript file:

// ==UserScript==
// @name           Code highlight
// @description    Test
// @include        http://localhost/*
// @version        1.0
// ==/UserScript==

var js = document.createElement('script');
    js.src = "http://localhost/test/js/load.js";
    document.getElementsByTagName("head")[0].appendChild(js);
    js.onload = function(){
        console.log(A)
    }

The content of the load.js file is as follows:

var A = {
    name:'aa'
}


In Google Chrome, the console displays "undefined", even though the load.js file has been fully loaded.

I have tested the userscript in Firefox and it correctly outputs A.

Answer №1

Avoid using .onload, .onclick, etc. in a userscript. (This is considered bad practice even on a regular web page).

The reason for this recommendation is that userscripts are restricted within a sandbox ("isolated environment"), which limits the ability to set or access page-wide JavaScript objects in a Chrome userscript or content-script.

Instead, always opt for using addEventListener() (or similar functions from libraries like jQuery's .on()). Additionally, it is advisable to establish load listeners prior to injecting <script> elements into the DOM.

If you need to reach variables in the page scope (such as B here), you will need to insert code that facilitates this operation. (Alternatively, you can consider switching to Tampermonkey and utilizing unsafeWindow, though there have been reported issues with this approach due to Chrome 29 compatibility problems.)

Consider employing something along these lines:

addJS_Node (null, "http://localhost/test/js/load.js", null, executeAfterLoad);

function executeAfterLoad () {
    addJS_Node ("console.log (B);");
}

//-- The addJS_Node function follows standard practices
function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    if (runOnLoad) {
        scriptNode.addEventListener ("load", runOnLoad, false);
    }
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targetElement = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    targetElement.appendChild (scriptNode);
}


Alternatively:

addJS_Node (null, "http://localhost/test/js/load.js", null, executeAfterLoad);

function executeAfterLoad () {
    addJS_Node (null, null, myScriptThatUsesPageJS);
}

function myScriptThatUsesPageJS () {
    console.log (B);
    //--- ADDITIONAL FUNCTIONALITY CAN BE INCLUDED HERE.
}

... ...

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

Adjust the sliders according to the current time

I am looking to display different sliders based on the time of day. For instance, 'slider set 1' from 0-9am, 'slider set 2' from 9am-12pm, and so forth. I am new to java script and need assistance in solving this challenge. Below is the ...

By utilizing jQuery, I am orchestrating the movement of a series of div elements within a container with the simple click of a button

A group of div elements located within a container. When the button is clicked, the train should start moving. <script> $('document').ready(function(){ $("button").click(function(){ $("#train").animate({left: "300px"}, 2000); ...

JQuery Tic Tac Toe Duel: Face Off Against Your Friend in a Thr

Looking for some advice here. I'm new to game development and currently working on a 2 Player Tic Tac Toe game. I need help with implementing the game functionality. Any suggestions? I want to disable the "div" once a player clicks on it, but I' ...

Despite reaching a video readystate of 4 in HTML5, the video still hangs and does not play smoothly

Using html5, I am currently working with video and audio. I have encountered an issue where sometimes the video hangs even after its readyState === 4. The cause of this problem is unclear to me. I aim for a solution where if the video's readyState = ...

Having trouble modifying a nested object array within a treeview component in Reactjs

Thanks for your help in advance! Question: I'm having trouble updating a nested object of an array in a treeview using Reactjs. Please refer to the code and sandbox link below: https://codesandbox.io/s/cocky-leakey-ptjt50?file=/src/Family.js Data O ...

WebStorm failing to identify Node.js functions

I recently began my journey in learning node.js and I'm currently utilizing WebStorm 11 as my preferred IDE. However, I've encountered an issue where WebStorm does not seem to recognize the writeHead method: var http = require("http"); http.cre ...

Guide on associating user IDs with user objects

I am currently working on adding a "pin this profile" functionality to my website. I have successfully gathered an array of user IDs for the profiles I want to pin, but I am facing difficulties with pushing these IDs to the top of the list of profiles. My ...

When HTML/JS code is utilized, the submit button or image should function to open the same page as

In addition to the left and right mouse buttons, you also have a middle mouse button. If you click on an image or hyperlink with this middle mouse button while browsing any website, it will open a new window in the background. Now, I want to achieve a sim ...

I'm curious about how I can selectively utilize vuex-persistedstate with Nuxt for certain stores only

Check out this library: https://github.com/robinvdvleuten/vuex-persistedstate. I have customized the provided plugin file for Nuxt. import createPersistedState from 'vuex-persistedstate' export default ({ store }) => { createPersistedState ...

Having trouble with rendering prop values in Vue.js?

Struggling to develop an ajax form component in vuejs within a Laravel 5.3 application. It seems I am facing some challenges with displaying the form fields. Can someone lend me a hand? Here is the front end code for rendering the form: <ajax-form ...

Tips for implementing a custom filter in an AngularJS JavaScript controller

Can anyone help me with creating a custom filter in an AngularJS JavaScript controller? I need to be able to search for items in an array called segments by their SegmentId. The filter should iterate through the segments array and return the segment that ...

Issue with MUI Data Grid sorting: Data Grid sortComparator function returning undefined

I'm attempting to organize data with nested values in a data grid, but I keep receiving 'undefined' on the sortComparator of Data Grid Columns. Code: Column Data Setup: { headerName: 'Title', field: `${this.props.type} ...

The accuracy of the fromPointToLatLng function in Google Map's JS API seems to be inconsistent with the actual events

My objective is to enhance user experience with a drawing tool on the map interface. I aim for a functionality where, upon single-clicking somewhere on the map using tools like the rectangle tool, the map automatically centers on that clicked location. Thi ...

Running npm commands from the root directory while the package.json file is located elsewhere

Although I understand that it's not ideal, I am faced with a specific directory structure that cannot be changed: [projectRootDir] [src] [tests] [otherDirs] [configuration] package.json mocha.opts other files.. ...

Pattern matching using regex can also be used to restrict the number of characters allowed

Having some trouble with regex to match a specific pattern and also limit the number of characters: Let's say I have allowed number prefixes: 2, 31, 32, 35, 37, 38, 39, 41, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 I only want numb ...

Ways to verify if the CSS background-color is set to white?

I am looking for a solution: $('*').click(function() { if($(this).css("background-color") == "#ffffff") { $(this).css("background-color") == "#000000" } });​​​​ that will execute on click of a specific cla ...

Granting permission to use the camera and microphone in Chrome 64

I recently came across a helpful discussion in my quest to enable camera and microphone access in Chrome, but unfortunately the suggested methods haven't been successful for me. I tried both approaches outlined in the thread but without any luck. Desp ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

What methods can be employed to stop tests from being included in rollup bundles?

I am currently in the process of creating a react component package and I would like to know how to prevent my tests folder from being included in the dist file that is generated by rollup. After running rollup -c, my directory structure looks like this: ...

Finding the nearest span value upon clicking through a specific class

Whenever a user clicks on a hyperlink, my goal is to locate the nearest span element with a specific class and retrieve the text within that class. As of now, it is only returning blank text: Here is the provided HTML code snippet: <div class="plan re ...