如何从警报框中获取文本?

时间:2014-03-22 14:31:27

标签: javascript google-chrome greasemonkey

我需要从警告框中获取文字。

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

我没有足够的声誉来上传图片..所以我上传代码而不是图片:)

有没有办法从popup&#34;中获取文字&#34;在Chrome上使用Greasemonkey?

3 个答案:

答案 0 :(得分:2)

查询不清楚..但如果我理解正确..页面上有一个JavaScript会导致警告()

您可以从页面上的JavaScript获取该警报的文本。

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
  }
} 

在您的情况下,上述功能将返回某些文字

答案 1 :(得分:0)

从提示

获取用户输入
var name = prompt('Please enter your name');

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

得到是/否答案

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

if (response == true)
    console.log("You pressed OK!");
else 
    console.log("You pressed Cancel!"); 

答案 2 :(得分:0)

这是另一种有趣的方式(如果你不介意覆盖全局警报,提示和取消功能)......

// 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')