1

I'm trying to write js variable (tab.url.toString()) to html. I've tried to do this:

document.write(tab.url.toString())

but it's a part of a big js code and only this is related to html.

The html is called history.html and I wrote there:

<script src="nameFile.js"></script>

how can I connect between the js code and this specific html file?

Thanks.

4
  • 1
    There is no such thing as 'specific html file'. You add stuff to the DOM. Commented Mar 31, 2022 at 9:33
  • That specific HTML file would then have to execute the Javascript. You cannot "pass" JS from one page to another. Commented Mar 31, 2022 at 9:35
  • can't I save the variable and pass it to the html? Commented Mar 31, 2022 at 10:09
  • You can store it in localStorage for example, which you can then read on the target page. Commented Mar 31, 2022 at 11:18

2 Answers 2

1

You can try and grab the element by its id in your Javascript file

someId = document.getElementById('someId')

Then you append the value to it by

let val = tab.url.toString()
someId.innerHTML = val
Sign up to request clarification or add additional context in comments.

Comments

0

Create variable on the global window object

You can create a property on the window object, something like this:

window.tabUrl = tab.url.toString();

This variable is globally accessable by every script that comes after its execution.
As long as you always write the full name window.tabUrl it will be available from anywhere.

You can use that value now in other scripts. Just as an example:

document.getElementById('exampleId').innerHTML = window.tabUrl;

Documentation for innerHTML:
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Using global variables on the window object should not be used too much, but it is an easy solution to transfer values for your personal projects.

2 Comments

Changes to the window object don't persist between requests.
Oh right I understood different HTML files as templates somehow. Nevermind : )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.