Frage

I need to get text from alert box.

<script type="text/javascript">
   alert('Some text')
</script>

I don't have enough reputation to upload images..so i upload code instead of image :)

Is there any way to get text "from popup" on Chrome using Greasemonkey?

War es hilfreich?

Lösung

Query is not clear ..but if I understand it correctly ..there is a JavaScript on a page that results in an alert()

You can get the text of that alert from the JavaScript on the page.

function getAlert() {

  // get all scripts
  var elem = document.scripts;

  // loop and check
  for (var i = 0, len = elem.length; i < len; i++) {

    var txt = elem[i].textContent.match(/alert\(['"]([^'"]+)['"]\)/);
    if (txt) { return txt[1]; } // if matched, return the alert text and stop
  }
} 

In your case, the above function will return Some text.

Andere Tipps

Here's another interesting way (if you don't mind overriding the global alert, prompt & cancel functions)...

// Wrap the original window.alert function...
const windowAlert = window.alert;

window.alert = function(message) {
  console.log(`window.alert called with message: ${message}`);
  return windowAlert(message);
};
alert('FOO');
// Console Output:
// window.alert called with message: FOO
// ========================================================


// Wrap the original window.prompt function...
const windowPrompt = window.prompt;

window.prompt = function(message) {
  console.log(`window.prompt called with message: ${message}`);

  const input = windowPrompt(message);
  console.log(`user entered: ${input}`);
  
  return input;
};
prompt('BAR');
// Console Output:
// window.prompt called with message: BAR
// user entered: xxx
// ========================================================


// Wrap the original window.confirm function...
const windowConfirm = window.confirm;

window.confirm = function(message) {
  console.log(`window.confirm called with message: ${message}`);

  const choice = windowConfirm(message) ? 'ok' : 'cancel';
  console.log(`user clicked: ${choice}`);
  
  return choice;
};
confirm('BAZ');
// Console Output:
// window.confirm called with message: BAZ
// user clicked: ok (or 'cancel' if you click 'cancel')

Get user input from a prompt

var name = prompt('Please enter your name');

if (person!=null) 
    console.log('The person's name is: ' + name);

Get a yes/no answer

var response = confirm('Press a button');

if (response == true)
    console.log("You pressed OK!");
else 
    console.log("You pressed Cancel!"); 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top