简体   繁体   中英

How do I inspect values and fields while developing a greasemonkey script?

Probably a very silly question, but I'm trying to make a simple thing like this:

var links = document.querySelectorAll ("a[href*='pattern'");
for (var J = links.length - 1;  J >= 0;  --J) {
    var link  = links[J];
    let myvar = "foobar";
    link.href = `https://example.com${myvar}`
}

This is just simple text replacement, and the above code works in the sense that it does replace the links.

But what I find a mess is that my development feels so much like just trial and error. I modify the code. If nothing happens on the page when I update, then I know that's something is wrong. But this is extremely inefficient. My procedure is something like trying code like this:

var myvar=link.text;
alert(myvar);

Then I update the page. If nothing shows up at all, then link probably didn't have a field called text. I realize that people developing greasemonkey scripts for certain are doing this in a much more efficient manner, via a console or something. But I just cannot figure out where to start. How would I approach the above? How to figure out available fields and methods in an object? How to inspect their values?

Here is an example based on your code ...

Updated based on comment

// To view logged message, open Developer tools for THAT page 
// e.g. F12 in Firefox/Chrome

const myvar = 'foobar';

// get the target links
const links = document.querySelectorAll('a[href*="pattern"');
console.log('links', links);

// run a loop on the links
links.forEach(a => { 
 
  console.log('link url before change', a.href);
  a.href = 'https://example.com' + myvar
  console.log('link url after change', a.href);

  // if you need link text
  console.log('link text', a.textContent);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM