Reputation: 19
Consider an HTML
page named page1.html
with the following simple structure:
<html>
<title>Page1</title>
<body>
<h1>Hello</h1>
</body>
</html>
Is it possible to change<h1>
text on page1.html
with JavaScript from page2.html
?
If it’s possible, how can one achieve this?
Upvotes: 1
Views: 271
Reputation: 4789
Since you commented that you don’t need it to be persistent, what you want is to create an illusion that you’re changing <h1>
text on page1.html
with JavaScript from page2.html
.
You need two things:
First, to change the actual text in <h1>
use .innerText
property with replace()
method.
To change the URL in the address bar from /page2.html
to /page1.html
use the History API
with history.pushState()
and history.replaceState()
methods.
Upvotes: 0
Reputation: 3095
I think the short answer you are looking for is "No".
You cannot modify one static page using another static page without a server between them.
Some solutions as mentioned from other pals can work, like using a local storage or stuffing a cookie -Only if they will run on the same browser-, but it will definitely require some changes in page1.html which is not you're looking for.
Upvotes: 2
Reputation: 7145
Assuming you serve both your HTML
S from the same origin (e.g. if you had two facebook tabs open), you could solve this by using the 'storage' event (Local Storage is shared between tabs), like this:
HTML1:
<script>
localStorage.setItem('message', JSON.stringify({ 'myContent': 'i like pizza' }));`
localStorage.removeItem('message');
</script>
HTML2
<script>
$(window).on('storage', e => {
var message = JSON.parse(e.originalEvent.newValue);
$('#myH1').text(message.myContent);
});
</script>
Upvotes: 4