Navigate to a different URL and add JavaScript code to it, then add additional JavaScript code to the modified URL

Is it possible to use a bookmark that appends JavaScript to a page in order to load another page and interact with its elements afterwards?

Here's what I'm attempting to achieve:

  1. Click on a bookmark that prompts for a search term
  2. Enter the search term and load a specified URL
  3. Automatically input the search term into the search box without changing the URL
  4. Execute the search on the new page

I've experimented with setInterval, setTimeout, onreadystatechange, hashchange... But each time, the script attached to the original page disappears once the new page is loaded. Is there a way around this?

Answer №1

It is evident that when a script loads a new URL in the current window, all scripts within that window are terminated and cannot interact with the newly loaded window.

In such cases, there are several options available:

  1. Embed the code to modify the newly loaded window into the startup sequence of the page itself so that it automatically executes upon loading.

  2. Pass arguments to the new page as query parameters in the URL and utilize code on the new page to process these parameters and carry out desired operations during startup. Even though the implementation code must be on the new page, this method allows for customization by attaching query parameters to the loaded URL. For example, if loading a URL like http://whatever.com/foo.html, you can append query parameters such as

    http://whatever.com/foo.html?show=price&user=bob
    for the startup script on that page to interpret and act upon. This enables passing arguments from the URL loader to the startup code in the page.

  3. Identify an external window capable of loading the new URL and monitoring its loading progress. Once the load is complete, run a script to make modifications. Both windows must belong to the same domain (same origin) for JavaScript to permit this interaction.

Answer №2

Of course, @bummi, that's a valid point. Below are the JavaScript files mentioned in the link.

I. JS File 1

To add this to your document, create a bookmark with the following URL structure:

javascript:(function(){document.body.appendChild(document.createElement('script')).src='jsFile1.js';})();

The code of jsFile1.js:

Create a variable to hold a new <iframe> element:

var ifrm = document.createElement("IFRAME");

Specify the page you want to load into the iframe (<iframe>):

ifrm.setAttribute("src", "http://www.monkeyseatkoalas.blahblah"); 

Add some style to the iframe:

ifrm.style.width = 100+"%"; 
ifrm.style.height = 600+"px"; 

Append the new <iframe> to the body of the current page. Note: Loading pages in an iframe only works when they belong to the same domain as the parent page.

document.body.appendChild(ifrm);

We now have an iframe on our page with a positional index of [0]. To manipulate this page easily, let's attach another JavaScript file to it using the following code:

frames[0].document.body.appendChild(frames[0].document.createElement('script')).src='jsFile2.js';

II. JS File 2

Ensure everything is loaded before performing any actions to access required elements or perform calculations based on them. You can run the following code once the page is fully loaded:

window.onload = function () { // additional code below...

You can use ".forms" for easy access. For example, assign an ID to a form if it doesn't have one already:

document.forms[numberOfFormElementOnThePage].setAttribute('id', 'mySpecialCupcakeFormCheeseName');

Next, get a reference to the form by its ID:

var getDatForm = document.forms["IDofYourForm"];

Locate and store the input box where you want to enter data. Use the .elements[x] method to access specific elements within the form:

var getDatSearchBox = getDatForm.elements[1];

Prompt the user to provide a search term and store it in a variable:

var nameToFind = prompt('Word to search for? Name? Ice cream? Doggy?');

Update the value of the search box (stored in the variable getDatSearchBox) with the entered text:

getDatSearchBox.value=nameToFind;

Finally, submit the form:

document.forms["users_search"].submit();
};

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

A guide to generating numerous SVG paths using a JavaScript function

Creating strokes with similar length but different angles of rotations can be achieved efficiently using JavaScript instead of writing redundant lines of code. The following code snippet demonstrates one way to achieve this: function stroke(rot) { var d ...

Error in Console while Json is not being displayed on the Screen in React Native

Encountering an issue while attempting to display JSON data from mongodb on the screen of a React Native Application. The screen is visible but no data is showing up. Below is the error message along with the code snippet. This is a basic hello world appli ...

JavaScript for URL encoding

Hey there, I've been using the function below to encode my data and send it through the GET method. I'm utilizing AJAX for sending and PHP for receiving. function urlencode(a){ a=encodeURIComponent(a); a=a.replace(/\\/g,&apos ...

Simultaneous activation of two click events in Javascript

I am looking to create a game using JavaScript. The game will be designed for two players to play on the same mobile device. I am facing a challenge with coordinating the players' clicks, as they may happen simultaneously. I have attempted to use bot ...

JSON and jQuery-powered Select List generates empty options when appended

When a user enters their zip code, an AJAX request is made to the server to retrieve associated cities. I want to use the JSON data returned from this request to populate a select list and replace the existing text box for city. For instance, if a user en ...

Automated album creation through Ajax image uploader

For my wedding website, I wanted to allow guests to upload photos. I attempted to combine the functionalities of "Ajax Image Upload and Resize with jQuery and PHP" with an existing image gallery on my site. While both the HTML and PHP components work fin ...

In Internet Explorer 11, an error with code script5017 is triggered when attempting to utilize fortawesome

Below this statement, you can find the console error message: script5017 syntax error in regular expression chunk-vendors.js (96290,5) chunk-vendors.js !*** ./node_modules/core-js/modules/es.regexp.constructor.js ***! ... result = inheritIfRequired(Nativ ...

What is the best way to retrieve the innerHTML content of an anchor tag with Cheerio?

Looking to extract data from an HTML page, a simplified example is provided below. Upon running the code, I anticipate the output to be [ "foo", "baz", "quux", ] but instead encounter an error message stating "TypeError: anch ...

The comparison between form submission and AJAX request when transmitting data in JSON format

Working on a complex PHP/Drupal project, our team is facing the challenge of enabling a deep link into a page that requires extensive data to be passed from the originating site. We have full control over both ends so cross-domain issues are not a concern ...

Ajax requests are returning successful responses for GET and POST methods, however, no response is being received for

When I make a POST request within the same domain ( -> ), the responseXML contains the expected data. However, when I make the same request as a PUT, the responseXML is null for a successful request. I have tried using jQuery.ajax and even implemented i ...

Is it true that Async methods in Typescript return promises?

I'm currently in the process of familiarizing myself with Async/Await in Typescript. I've been updating existing code, for example: getImportanceTypes(): Promise<void> { return this.importanceTypeService.list() .then(i ...

Leveraging the power of THREE.js TransformControls

I am currently working on a project in JSBin and attempting to incorporate the THREE TransformControls class. Due to constraints, I am unable to share my full code, but my JavaScript is contained within <script type="text/javascript"></s ...

The function parameter containing the symbol "[," signifies

I keep coming across this syntax [, everywhere and I'm baffled by its meaning. d3.mean(array[, accessor]) .on( events [, selector ] [, data ], handler ) Why is there a comma after the opening bracket? What does it signify? ...

What is the best method to save a screenshot to your local drive without any annoying pop-ups?

I am looking to save a screenshot locally without displaying a download popup. (function() { 'use strict'; $("body").prepend(` <button id="btCapture">SCREENSHOT</button> <input type="sub ...

Turn off the second dropdown menu if the first one has not been chosen

I need to implement a feature where the second dropdown is disabled if the first dropdown is not selected. Is there a way to achieve this using JavaScript? The requirement is that if the user does not select an option from the first dropdown, the second dr ...

What are some effective methods to completely restrict cursor movement within a contenteditable div, regardless of any text insertion through JavaScript?

Recently, I encountered the following code snippet: document.getElementById("myDiv").addEventListener("keydown", function (e){ if (e.keyCode == 8) { this.innerHTML += "&#10240;".repeat(4); e.preventDefault(); } //moves cursor } ...

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 ...

Having trouble getting sound to work on React app when running locally

When I run my application on codesandbox, the audio plays without any issues. However, after importing my React application locally, I keep encountering an error message whenever I try to trigger the audio play prompt in my program: DOMException: Failed t ...

Tips for properly implementing ng-hide and ng-show across various sections of your single page application

Currently working on a Single Page Application (SPA). I've included some buttons in the side navigation with the intention of displaying different content when they are clicked. However, I encountered an issue where using ng-hide and show didn't ...

Extract the text from the first column of a table using an onclick event

I'm currently struggling with this issue and can't seem to figure it out. My goal is to retrieve the text from the first column, which contains the room number. Here is the progress I've made so far: $.each(eval(data), function(index, item) ...