0

I am trying to automate navigation through search results. For instance, amazon's search results page like this one (purposely small). I can't find many posts on the topic, and most of what is out there like this one mention handling events such as window's popstate, hashchange. But they will not fire.

Code snippet:

window.addEventListener('popstate', () => console.log('pop state changed'))
window.addEventListener('hashchange', () => console.log('hash changed'))

document.location.assign('/s?k=comic+books&i=digital-text&rh=n%3A156104011%2Cp_n_feature_thirty-three_browse-bin%3A18116648011&dc&page=2&qid=1588508957&rnid=18116644011&swrs=A812F8AB9BA7A775DB9E4C23ADDCD5B3&ref=sr_pg_1') 
//tried ...location = '...' as well

Tried document.onload as well... to no avail. Seems like the window object is reset when document.location changes (properties I attach to the windows object are lost after document.location changes)

I want to automatically start executing some code after I manually navigate to the next results page. How do I accomplish that ?

David784
  • 7,031
  • 2
  • 22
  • 29
Veverke
  • 9,208
  • 4
  • 51
  • 95
  • 1
    How are you trying to run this JavaScript? A browser extension? Something like PhantomJS? – Quentin May 03 '20 at 13:27
  • On the browser (I plan to make it an extension, at the end). For the time being, everything is being done in Chrome's console. – Veverke May 03 '20 at 13:28
  • The answers are **very** different in an extension and the console. If you're going to develop an extension, then do that and react the extensions API documentation. – Quentin May 03 '20 at 13:52
  • what about sticking with Google Console for now ? Before someone closes (?!) the question... – Veverke May 03 '20 at 13:59

1 Answers1

1

You can't. A browser's Console runs code in the context of the current page.

If you navigate to a new page then the environment the code was running in goes away and so does everything the code you run in the console left in memory (such as variables and event handlers).

You need to write a browser extension to achieve this.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • All right, thanks for the lead. By the way, the main problem is that I do not have a way to automatically run code after that event, am I wrong ? Because we can workaround the absence of code by simply storing a function in localStorage as text and loading it with new Function in the new document. Tried that and it seems to work. – Veverke May 03 '20 at 14:09
  • Ok, so 2 weeks passed while I have been doing homework :) I am developing an extension, it's working, now I need to solve the problem posed in this question. I read that the solution is using chrome.tabs.onUpdate.addListener, is this the correct approach ? I did not have success yet neither listening in the content nor background scripts. – Veverke May 17 '20 at 14:31