Match and replace full javascript function - javascript

How can I match whole JavaScript function on current page? My JavaScript function is:
window.onbeforeunload = function()
{
if( !success )
{
success = true;
alert('Think first! Click CANCEL on the next page to receive a new gift.\n\n');
window.location = 'http://www.mysite.com/';
return '\nClick CANCEL\n\nOver thousands of gifts have been given out, get yours today!\n\n';
}
}
and I want dynamically match and replace this function to:
window.onbeforeunload=function()
{
return ExitPopup();
}
Please help me to resolve this.

can't you do
var newFunction = function()
{
return ExitPopup();
}
and then
window.onbeforeunload = newFunction;

Related

localStorage is null, but only from one function and not another

I have a PHP page that loads two JS files at the end. In the first file I have this...
// global variables
var refineSearchStorage = {};
// function calls
window.addEventListener("load", function() {
refineSearchStorage.get();
});
refineSearchStorage = {
data : null, // empty storage
get : function() {
refineSearchStorage.data = localStorage.getItem("refineSearchStorage");
if(refineSearchStorage.data === null) {
refineSearchStorage.data = { refineKeywords: '' };
refineSearchStorage.save();
}
else {
refineSearchStorage.data = JSON.parse(refineSearchStorage.data);
}
},
add : function(x) {
refineSearchStorage.data.refineKeywords = x;
refineSearchStorage.save();
},
save : function() {
localStorage.setItem("refineSearchStorage", JSON.stringify(refineSearchStorage.data));
}
};
Inline javascript calls Function 1 from the middle of the page. It is created by PHP after a search result...
<script>
window.addEventListener('load', function () {
searchActions('{$keywords_human}');
});
</script>
Function 1 appears in the 2nd JS page and the result is Uncaught TypeError: Cannot set property 'refineKeywords' of null... instead of adding to the localStorage.
function searchActions(x) {
refineSearchStorage.add(x);
}
Function 2 below is called with the click of a button and adds to a localStorage variable without issue. It is also located on the 2nd JS page...
function keywordAdd(y) {
var existingParams = refineSearchStorage.data.refineKeywords;
var param = y.toLowerCase();
var newParams;
newParams = (existingParams + ' ' + param).trim();
refineSearchStorage.add(newParams);
}
Function 1 used to work, but I did something to break it when I split the functions on to different pages. What did I do?
It's because
window.addEventListener('load', function () {
searchActions('{$keywords_human}');
});
gets called before
window.addEventListener("load", function() {
refineSearchStorage.get();
});
That error means that your data attribute is null
(screenshot) See what I mean by that
convert add to
add : function(x) {
refineSearchStorage.data = refineSearchStorage.data || {}; // this might help
refineSearchStorage.data.refineKeywords = x;
refineSearchStorage.save();
},

Disable alert Message

How can I disable certain alert on the page and allow others?
I tried With this code:
window.alert = function ( text ) {
console.log(text);
if(!text.includes("rambo"))
alert("rambo");
};
This won't work because it calls alert again and not the alert.
I need to use javascript alert( not any other libraries)
Save a reference to the old window.alert first.
const oldAlert = window.alert;
window.alert = function ( text ) {
console.log(text);
if(!text.includes("rambo"))
oldAlert(text);
return true;
};
window.alert('ram');
window.alert('rambo');
The other two answers are mostly correct, but they pollute the global namespace by creating a new reference to window.alert. So I would suggest wrapping this in an IIFE:
(function() {
var nativeAlert = window.alert;
window.alert = function(message) {
if (message.includes("test")) {
nativeAlert(message);
}
};
}());
alert("Hello"); // Doesn't show up.
alert("Hello test"); // Works.
nativeAlert("test"); // Throws an error.
You could go a step further an create an alert function generator that creates an alert object using a predicate:
function alertGenerator(predicate) {
if (typeof predicate === "function") {
return function(message) {
if (predicate(message) === true) {
window.alert(message);
}
}
} else {
return undefined;
}
}
// Create an alert generator that requires the word "test" in it:
var testAlert = alertGenerator(t => t.includes("test"));
testAlert("Hello"); // Doesn't show up.
testAlert("Hello test"); // Works.
// Create an alert generator that requires the word "Hello" in it:
var helloAlert = alertGenerator(t => t.includes("Hello"));
helloAlert("Hello"); // Works.
helloAlert("Hello test"); // Works.
helloAlert("Test"); // Doesn't work.
You can store old alter in variable
var ar = alert;
window.alert = function(text) {
console.log(text);
if (!text.includes("rambo"))
ar("rambo");
return true;
};
alert('dfs');
If you don't wan't to pollute global namespace or use an IIFE, why don't you simply wrap window.alert in another function like this:
function myCustomAlert(message) {
return message.includes('rambo') ?
window.alert(message)
: false;
}
myCustomAlert("This message won't be shown!");
myCustomAlert("This message will be shown because it contains rambo");

Recursively parse Google search results using CasperJS

I'm using the below CasperJS script to recursively parse the (multi-page) search results provided by google for the query site:https://www.launchgood.com/project/.
var links = [];
var casper = require('casper').create();
function getLinks() {
var currentLinks = document.querySelectorAll('h3.r a');
return Array.prototype.map.call(currentLinks, function(e) {
rawHref = e.getAttribute('href');
urlPattern = /.*(https?[:/]+[^&]+).*/g;
cleanHref = urlPattern.exec(rawHref);
return cleanHref[1];
});
Array.prototype.push.apply(links, currentLinks);
this.echo(' - ' + currentLinks.join('\n - '));
}
function parseAndContinue() {
links = this.evaluate(getLinks);
// now click 'Next'
if(this.exists('a.fl')) {
this.thenClick('a.fl');
this.then(parseAndContinue);
} else {
this.exit();
}
}
casper.start('http://google.com/ncr', function() {
// search from google form
this.fill('form[action="/search"]',
{ q: 'site:https://www.launchgood.com/project/' }, true);
});
casper.then(parseAndContinue);
casper.run();
This seems to continually search the 2nd page, over and over again in a never-ending loop -- instead of advancing to the next page.
What am I doing wrong?
Your looks fine apart from not printing anything. getLinks is a function that is evaluated in the page context. this refers to the global object, which is window, inside of the page context. You have no access to casper inside of the page context, because it is sandboxed and only primitive objects can be passed in or out. It has no access to variables defined outside of it (no access to links).
function getLinks() {
var currentLinks = document.querySelectorAll('h3.r a');
return Array.prototype.map.call(currentLinks, function(e) {
var rawHref = e.getAttribute('href');
var urlPattern = /.*(https?[:/]+[^&]+).*/g;
var cleanHref = urlPattern.exec(rawHref);
return cleanHref[1];
});
}
function parseAndContinue() {
var links = this.evaluate(getLinks);
console.log(JSON.stringify(links, undefined, 4));
// now click 'Next'
if(this.exists('a.fl')) {
this.thenClick('a.fl');
this.then(parseAndContinue);
} else {
this.exit();
}
}
Additionally, no code after the return statement will be executed.
Please be more careful and don't create global variables left and right.

Function Javascript return

Can you check if I return a function correct:
JS
$(eachsection).each(function() {
listfunction();
}
function listfunction(){
$(this).show();
$(this).find('a.q_weblinksprite_med').attr("onclick", construct_url);
$(this).find('.q_weblinksprite_med').text(itemTitle);
$(this).find(".status").text(itemStatus);
$(this).find('.q_rt_rowcell-1-title').text(itemCategory);
$(this).find('.q_clipline').html(itemContent);
}
What I want is just to return all content from listfunction(). Thanks!
The code you posted isn`t returning anything.
By the look, you could return a array
function listfunction(){
var myReturn = {};
$(this).show();
myReturn['url'] = $(this).find('a.q_weblinksprite_med').attr("onclick", construct_url);
myReturn['title'] = $(this).find('.q_weblinksprite_med').text(itemTitle);
myReturn['status'] = $(this).find(".status").text(itemStatus);
myReturn['category'] = $(this).find('.q_rt_rowcell-1-title').text(itemCategory);
myReturn['content'] = $(this).find('.q_clipline').html(itemContent);
return myReturn;
}
Is this what you are looking for?
Calling listfunction() from where you have it will cause you to lose scope. So if you are attempting to call $(this).show() and have it show the element you looped through, you would need to call it like this:
$(eachsection).each(function() {
listfunction(this);
}
function listfunction(element){
$(element).show();
$(element).find('a.q_weblinksprite_med').attr("onclick", construct_url);
$(element).find('.q_weblinksprite_med').text(itemTitle);
$(element).find(".status").text(itemStatus);
$(element).find('.q_rt_rowcell-1-title').text(itemCategory);
$(element).find('.q_clipline').html(itemContent);
}

How do I loop a check for string in a document in Javascript?

I'm trying to make a code that will search for a specific text, and if it is found it will click a button. It needs to check for the string continuously, however I am struggling to find a way for that to happen. I'm a complete newb to coding, so any help is appreciated! :)
var findMe = [
//Test
'Hello!',
];
function findText() {
var text = document.querySelector('div[id=BtnText]');
for (var i = 0; i < findMe.length; i++) {
if (BtnText.match(findMe[i])) {
var btnDo = document.querySelector('input[type="submit"][value="Click!"]');
if (btnDo) {
btnDo.click();
}
}
}
}
Just editing your code a little bit.
I am assuming you have HTML like this?
<div id="BtnText">Hello!</div><input type="submit" value="Click!">
You will to change your code to this
var findMe = [
//Test
'Hello!',
];
function findText() {
var div = document.querySelector('div[id=BtnText]');
for (var i = 0; i < findMe.length; i++) {
if (div.innerText.indexOf(findMe[i]) !== -1) {
var btnDo = document.querySelector('input[type="submit"][value="Click!"]');
if (btnDo) {
if (typeof btnDo.onclick == "function") {
btnDo.onclick.apply(elem);
}
}
return true;
}
}
return false;
}
If you want to check continuously. I recommend using setInterval.
var interval = setInterval(function() {
var textFound = findText();
if(textFound) {
clearInterval(interval);
}
},50);
Regular expression:
(new RegExp('word')).test(str)
(new RegExp(/word/)).test(str)
indexOf:
str.indexOf('word') !== -1
search()
searches a string for a specified value, or regular expression, and returns the position of the match.
var n=str.search("word");
or
var n-str.search(/word/);
if(n>0)
{}
with window.find()
if (window.find("word", true)){}
//code
while(window.find("word",true){
//code
}
Why do you need to perform the check continously?
You should get another approach... Or your script will be blocked by Chrome, for example, if it makes the page non responsible. You can go for a timeout, as Taylor Hakes suggested... Or just call your findText function attached to the onChange event on the div.

Categories