-1

I want to call a javascript method of a seperate page which is no were related to my page using a link..How do I do it??

Rameshj
  • 81
  • 2
  • 6
  • 1. Where is your try 2. You can't manage code out of your page with javascript – LellisMoon Mar 07 '17 at 15:02
  • Basically, you can't. The function needs to be linked to your page by either being on the page OR by including the containing JS file in your webpage – Sanchit Mar 07 '17 at 15:03
  • 1
    Also if you really need to do that, just go to the function declaration and copy the function to your code – Sanchit Mar 07 '17 at 15:04

2 Answers2

2

You can't.

JavaScript is prevented from accessing the page to trigger functions in it by the same origin policy.

Links are just links and can't trigger JavaScript automatically. For a link to trigger the JS you would have to pass data to the page (e.g. via the URL's query string) and the author of the page would have to write code to examine the query string and call functions based on that.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • @AndersonGreen — Not when the JS needs to run in the page that will be loaded only after the link has been followed and the current page (in which the JS is running) is unloaded. None of the methods your link suggest will work *in the context* provided by this question. – Quentin Jan 26 '21 at 21:22
  • If the page were opened in an iframe, it would be possible to [call a child method](https://stackoverflow.com/q/251420/975097) from the page that opened it. – Anderson Green Jan 26 '21 at 21:27
  • 1
    @AndersonGreen — The question doesn't say that an iframe is involved. It's just a regular link … to another website (and even if it was in an iframe, the same origin policy would block an attempt to call a method through it) – Quentin Jan 26 '21 at 21:28
0

That's not how it works. You can't call a javascript function from another page. If you want to use the same javascript functions on both pages, the right solution is to put the function in a separate javascript file you will call from both pages. You need to include something like this in your html documents:

<script language="javascript" src="yourfile.js">

Then, you will be able to use the functions in both html pages.

Alexis Dufrenoy
  • 11,784
  • 12
  • 82
  • 124