Ways to create interaction between two web pages with JavaScript

I am attempting to design a webpage where one page can influence the content of another page. I have two HTML pages and a JavaScript file named "Controll.js" which contains a function that changes the content of "Indiv" in Index.html. This function is triggered by a button on Controll.html. Here is my code:

 function myFunction() {
    document.getElementById("Indiv").innerHTML = "Hi!!";
 }
<!-- Controll.html -->

<!DOCTYPE html>
<head>
</head>
<body>


    <button type="button" onclick="myFunction()">write hi</button>

</body>
<script src="Controll.js"></script>
</html>
<!-- END Controll.html -->

<!-- Index.html -->

<!DOCTYPE html>
<head>
  <script src="Controll.js"></script>
</head>
<body>


  <p id="Indiv"></p>

</body>

</html>
<!-- END Index.html -->

Answer №1

When you navigate from one page to another, the Javascript code you write on the first page disappears. However, there is a way to make data persistent using "localStorage". To achieve this, you need to save the string in local storage from the controller and then retrieve it in the index page.

This is how the function should be implemented in Controll.js:


function myFunction() {
    localStorage.setItem('message', 'hi');
}

After implementing the function, you can trigger it on click just like in Controll.html:


<!-- Controll.html -->

<!DOCTYPE! html>
<head>
</head>
<body>

<button type="button" onclick="myFunction()">write hi</button>

</body>
<script src="Controll.js"></script>
</html>
<!-- END Controll.html -->

In index.html, we need to check if the Controll page has sent us any message. If a message is received, it will remain permanently by default. If you only want to send it once, you can delete it after fetching it.

Here's how it can be done in index.js:


var Indiv = document.getElementById('Indiv');

function fetchMessage(){
    // Check if the message exists
    if(localStorage.getItem('message')){
        Indiv.innerHTML = localStorage.getItem('message');
        // Optionally, empty the localStorage after retrieving the message
        localStorage.removeItem('message');
    }
}

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

What is the process for populating the Body placeholder in asp.net Core MVC?

After reviewing a tutorial, I discovered that the RenderBody method is supposed to display views within the designated placeholder of the layout, as illustrated in this diagram: https://i.sstatic.net/nJLUm.png However, in practice, it did not work exactl ...

Clicking activates Semantic UI's dropdown function with the onClick method

I am experiencing an issue with the dropdown functionality on my website. Everything works fine until I add onClick() to the Semantic UI component. It seems like there are some built-in functions for handling onClick() within Semantic UI, so when I impleme ...

Is it possible to incorporate npm modules into a browser and utilize them locally on a personal computer?

This is my first time working with npm modules and node.js, so I find it quite challenging. I have a JavaScript code with multiple data points and I need to find the closest city to each of them. In response to another question on Stack Overflow (Reverse ...

Tips for building and implementing Angular URL Parameters for URLs in the form: "component/#/?id=..."

I am currently facing a situation where I have an application with an existing user base. I am looking to avoid disrupting their current links for a smoother transition. However, the previous links are in this format: (server)/viewer/#/?id=12. Please see t ...

Unbind a prepared statement in a node.js environment using SQL

Utilizing the node-mssql library (https://github.com/patriksimek/node-mssql) and encountered a problem when attempting to execute a second request, resulting in the following error: this.connection.pool.acquire(done); ^ TypeEr ...

Is it possible to target a dynamically inserted p tag along with its child button using JavaScript?

I have a dynamically added paragraph element within a div that is already in the DOM. My goal is to use the button inside the paragraph to remove the entire paragraph itself. <div class="prime_ben"> <p class=”beneficiary”> ADDED: John C Sm ...

Using Bootstrap to transform date format to mm/dd/yyyy

In my Django web application, I am utilizing Material Kit (Bootstrap) for the front end. My goal is to display the date on the HTML page in the format of mm/dd/yyyy. For example: 06/27/2018 The date in the database table is already stored in the forma ...

When altering the color of a mesh in Three.js, only a single face is impacted by the modification

I have a GLB model with multiple parts and hierarchy. My goal is to highlight a specific part of the assembly on mouseover. The code snippet I am using for this functionality is as follows: raycaster.setFromCamera( pointer, camera ); ...

A serene web service that delivers XML data

I'm currently trying to navigate a restful webservice that responds with xml data. I'm fairly new to working with restful web services, so I'm feeling a bit lost on what steps to take next. From what I understand, it seems like the issue lie ...

Learn the process of directing to a view in a jQuery AJAX call with Spring MVC

Below is the ajax call I am using: $.ajax({ type: "POST", url: contextPath +"/action", cache:false, dataType: 'text', data: {Id:Id}, success: funct ...

What is the best way to design versatile div containers that combine the float property with fluid dimensions?

I am attempting to achieve a specific layout where the width of the content_container extends up to the right side of the screen and dynamically adjusts based on whether the expandable pane is collapsed or expanded. Applying width: 100% to .content_contain ...

The call to Contentful's getAsset function resulted in an undefined value being

I am facing a challenge while trying to fetch an asset, specifically an image, from Contentful and display it in my Angular application. Despite seeing the images in the Network log, I keep encountering an issue where the console.log outputs undefined. Any ...

Converting a Disable submit button from jQuery to alpinejs: A Step-by-Step Guide

Is there a way to convert the disabling of a submit button using jQuery to Alpine.js? The Code : <form> <input type="text" class="input-field" placeholder="Enter you name *" value="" /> <button ty ...

Instructions for setting a default value for ng-options when dealing with nested JSON data in AngularJS

I need help setting a default value for my ng-options using ng-init and ng-model with dependent dropdowns. Here is an example of my code: <select id="country" ng-model="statessource" ng-disabled="!type2" ng-options="country for (country, states) in c ...

Can the Disqus API be leveraged to retrieve comments from a particular website address?

It is my preference to accomplish this task solely with client-side JavaScript scripting, if feasible. ...

What is the best way to combine two responses and then convert them into a promise?

When making two calls, the firstCallData prints data fine. However, when I use + to merge the responses, it returns me the following Response. What is a better approach to achieve this task? main.ts let data = await this.processResponse(__data.Detail ...

Is the tablesorter jQuery plugin not functioning properly with Flask or dynamically generated tables using for loops?

The Issue My Flask web application generates an HTML table using a for-loop. I am having trouble making this table sortable, even though I can successfully sort demo tables that are not generated with for-loops. Here is the code snippet: index.html {% e ...

Angular: Modify value when checkbox is ticked

Controller: promiseObj.physical = $http.get('search?sumBoth=1&customer=' + customer).success(function(data) { $scope.servers = data; // retrieve data from JSON }); View: <tr ng-repeat="data in servers | filter: { _id: { idc: item._ ...

Unchecking and checking the radio button is necessary in order for it to function properly

Today, I'm puzzled by the odd behavior of my radio buttons in a pixel drawer project. In order for the radio button to function properly, I have to uncheck it and then recheck it. The pixel drawer allows me to change colors and sizes using these radio ...

Autocomplete for Converting Postal Codes to Cities

I'm currently working on a project that involves two input fields, as shown below: <div class="form-group{{ $errors->has('plz') ? ' has-error' : '' }}"> <label for="plz" class ...