Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text from alert box?

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?

like image 965
Gobrisebane Avatar asked Mar 21 '23 03:03

Gobrisebane


2 Answers

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.

like image 68
erosman Avatar answered Mar 28 '23 17:03

erosman


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')
like image 24
jmg Avatar answered Mar 28 '23 16:03

jmg