cchajar
cchajar

Reputation: 114

how to run a javascript code on an external website?

I've written a script by JavaScript and i'm running it on external websites (which that I don't own their domain such as Google or Stackoverflow) by opening the Inspector (F12), paste and run the script in the console.

Now I have 2 questions:

  1. Is there any way to run the code without doing above steps ?
  2. In some cases I click on a button and a new page would be load. How can I load that script on second page too ?

Upvotes: 0

Views: 2681

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370879

The easiest method would be to install a userscript manager like Tampermonkey. If you paste your code into a userscript, it'll run automatically on any sites that match the @include / @match directive of the metadata block.

In some cases I click on a button and a new page would be load . how can I load that script on second page too ?

If possible, put the URL of that second page into the metadata block of your userscript.

For an example of a userscript that runs on multiple pages:

// ==UserScript==
// @name             Some example
// @include          /^https://www\.google\.com*/
// @include          /^http://.example\.com/
// @grant            none
// ==/UserScript==

console.log('script running');

If you go to google.com and search for example.com, you'll see script running. Then if you click on the search result to example.com, you'll see script running on the other page too.

If the other URL isn't known in advance, it'll be harder. You'll probably need

// @match        *://*/*

(to have the script run on all pages) and somehow communicate to the new window that it should run the script as well, such as through a query string, or postMessage, or GM_setValue.

Upvotes: 2

Related Questions