How to call a Greasemonkey function when a JavaScript link is clicked - javascript

So I recently started working on Greasemonkey scripts without much prior experience in JavaScript. It was going fine until I hit this roadbloack.
I'm writing a script for a page that has a small table of information. If a link at the bottom is clicked, the table expands fully in the page to display all information. I need to call a function in Greasemonkey when this happens, however, the link doesn't appear to have an ID or anything I can actually reference to watch it. It's simply this:
When it's clicked, the table expands and it then shows as true. I initially used the following to expand the table upon loading the page, but that broke several things:
window.location.href = ('javascript: expandFullTable(false)');
I've attempted using "click", "onclick", and even "mouseover" to have Greasemonkey detect when it's pressed but nothing seems to work. From what I can tell it's simply a link that calls a function, but after some significant searching I wasn't able to find out anything about how to reference it in my script. I'm sure it's incredibly simple, but it's frustrated me to no end.

You can hijack the function like this:
var oldExpandFullTable = unsafeWindow.expandFullTable;
unsafeWindow.expandFullTable = function() {
// Do something
alert("You clicked on that thing!");
// Call the original function
oldExpandFullTable.apply(this, arguments);
};
But since you tagged this jquery this should let you retrieve the link:
var link = $("a[href^=\"javascript: expandFullTable\"]);
It should work if jQuery is injected into your script with #require. If it's already in the page, you can add this before to access it: var $ = unsafeWindow.jQuery;.
And by the way, perhaps you should learn more about unsafeWindow to avoid security holes.

Related

Changing an object properties then calling a function inside a custom function with javascript

Title is probably a little messy. Basically what I'm trying to do is to create a custom function that will modify an object properties, then return that object, and then call a function.
A little background on what I'm doing : Trying my best with the Zendesk API to use a web widget on my webpage. Basically this web widget is configured to be a HelpCenter on startup, which then shows a button for either live chat or email, depending on the state. The main property in question here is called 'suppress' which disables one of the widget pages (chat, email & helpCenter). And my goal is to make that custom function 'suppress' 2 of the 3 widget pages so it only shows one. Then a API func called zE.activate() would open up the widget.
I know this is a lot of text, let me show you the code I've got so far :
<script>
function setChatPopOutProps(window) {
window.zESettings = {
webWidget: {
contactForm: {
suppress: true
},
helpCenter: {
suppress: true
}
}
};
return window.zESettings;
};
function chatPopOut() {
setChatPopOutProps(window);
zE.activate();
};
</script>
Now when I click on the button that has chatPopOut() assigned, the zE.activate() works since it opens up the widget, but basically the setChatPopOutProps(window) didn't seem to work.
I also tried the following :
Not returning window or window.zESettings
Putting everything under a single function by putting zE.activate() at the end of zESettings or just after the return window or window.zESettings
If you need to see the widget in action to have an idea, you can see it right here. Click on the green button on the bottom right, type anything, and you'll see the contact form button pop up. This button changes for a chat button when a live chat agent is available.
Now I know this is something that I should normally work out with Zendesk directly, which I tried, but they told me that there's nothing that can do what I'm trying to accomplish, but I really feel like this has something to do with the way I'm doing things in javascript and not the way the API is built..
Does anyone have an idea ? I would really appreciate it.
P.S. This is my 2nd post, so I apologize in advance for mistakes I probably made in this question.
Sadly, it turns out that what you are trying to accomplish just isn't possible. As the zE.settings get applied when the widget is first initialized, so there is no way to dynamically alter the widget settings without doing an action such as refreshing the page and re-initializing the widget. As far I can see from your code, I dont think you want to refresh the page everytime, and reinitialize the widget just to apply those settings that you listed above.

Re-execute js on back without reloading the whole page

Is there a way to re-execute JS without refreshing a page?
Say if I have a parent page and an inside page. When the inside page gets called, it gets called via ajax, replacing the content of the parent page. When user clicks back, I would like to navigate them back to the parent page without having to reload the page. But, the parent page UI relies on javascript so after they click back, I would like to re-execute the parent page's javascript. Is this possible?
Edit: Here is some code. I wrap my code in a function but where and how would you call this function?
function executeGlobJs() {
alert("js reload success");
}
You could use the html5 history-api:
In your click-handler you'll call the pushState-method, stat stores the current state for later reuse:
$(document).on('click', 'a.link', function () {
// some ajax magic here to load the page content
// plus something that replaces the content...
// execute your custom javascript stuff that should be called again
executeGlobJs()
// replace the browser-url to the new url
// maybe a link where the user has clicked
history.pushState(data, title, url);
})
...later if the user browses back:
$(window).on('popstate', function () {
// the user has navigated back,
// load the content again (either via ajax or from an cache-object)
// execute your custom stuff here...
executeGlobJs()
})
This is a pretty simple example and of course not perfect!
You should read more about it here:
https://css-tricks.com/using-the-html5-history-api/
https://developer.mozilla.org/en-US/docs/Web/API/History_API
For the ajax and DOM-related parts, you should need to learn a bit about jQuery http://api.jquery.com/jquery.ajax/. (It's all about the magic dollar sign)
Another option would be the hashchange-event, if you've to support older browsers...
You can encapsulate all your javascript into a function, and call this function on page load.
And eventually this will give you control of re-executing entire javascript without reloading the page.
This is common practise when you use any concat utility (eg. Gulp)
If you want to reload the script files as if it would be on a page reload, habe a look at this.
For all other script functions needed, just create a wrapper function as #s4n989 and #Rudolf Manusadzhyan wrote it. Then execute that function when you need to reinit your page.
I'm having the same problem I don't use jquery.
I don't have a solution yet. I think that your problem is that it doesn't read all the document.getelements after you add content, so my idea is to put all the element declarations in a function. And than after the ajax call ends to call the function to get all the elements again.
So it might be something like that
Func getElems(){
const elem= document.getelementsby...
Const elem.....
At the end of the js file make a call for
the function
getelems()
And than at the end of the event of the
ajax call. Just call the function again.
Sorry that is something that comes to my mind on the fly while reading and thinking on the problem i have too:).
Hope it helped I will try it too when I will be on the computer :)
I believe you are looking for a function called
.preventDefault();
Here's a link to better explain what it does - https://api.jquery.com/event.preventdefault/
Hope this helps!
EDIT:
By the way, if you want to execute the JS on back you can wrap the script inside of
$('.your-div').on('load', function(e) {
e.preventDefault();
//your JavaScript goes here
}

Clicking a link does not refresh the content

I've been looking at how to automate actions on a webpage with PhantomJS, however I'm having issues manipulating the page to do what I want it to.
I'm using this as test site. I've managed to get Phantom to open the webpage and scrape the random sentence from the #result span. But now what I want to do is get another sentence without re-launching the script. I don't want to close and re-open the page as Phantom takes ages to launch the webkit and load the page. So I thought I could get another sentence by getting Phantom to click on the 'Refresh' button below the sentence box. Here's what I have at the moment:
var page = require('webpage').create();
console.log("connecting...");
page.open("http://watchout4snakes.com/wo4snakes/Random/RandomSentence", function(){
console.log('connected');
var content = page.content;
var phrase = page.evaluate(function() {
return document.getElementById("result").innerHTML;
});
console.log(phrase);
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
$("frmSentence").click();
});
});
var content = page.content;
var phrase = page.evaluate(function() {
return document.getElementById("result").innerHTML;
});
console.log(phrase);
phantom.exit();
});
As you can see I'm trying to click the refresh button by using a .click() function, but this isn't working for me as I still get the same sentence as beforehand. Given the HTML for the button:
<form action="/wo4snakes/Random/NewRandomSentence" id="frmSentence" method="post" novalidate="novalidate">
<p><input type="submit" value="Refresh"></p>
</form>
I'm not sure what I should be referencing in the script to be clicked on? I'm trying the form ID 'frmSentence' but that isn't working. I'm wondering if .click() is the right way to go about this, is there some way for Phantom to submit the form that the button is linked to? Or maybe I can run the associated script on the page that gets the sentence? I'm a bit lost on this one so I don't really know which method I should go with?
You have a problem with your control flow. page.includeJs is an asynchronous function. If you have some other statements page.includeJs, they are likely executed before the script is loaded and the callback is executed. It means in your case that you've read the sentence 2 times before you even trigger a click.
If you want to do this multiple times, I suggest to use recursion since you cannot write this synchronously. Also, since you want this to be fast, you cannot use a static setTimeout with a timeout of 1 second, because sometimes the request may be faster (you lose time) and sometimes slower (your script breaks). You should use waitFor from the examples.
Instead of loading jQuery every time, you can move page.includeJs up and include everything else in its callback. If you only need to click an element or if jQuery click doesn't work (yes, that happens from time to time), you should use PhantomJS; click an element.
web scraping is about sending require information to a web server and get the result. It is not about behaving like a user clicking button or entering search criteria.
All you need to do in this example is send a POST request to http://watchout4snakes.com/wo4snakes/Random/NewRandomSentence. The result is just text in page.content, it does not even need to evaluate. So to get more than one sentence you just need to do a loop of page.open

Completely delete all instances of a div with a specific class using javascript/jquery?

I am using Popup.js by Toddish.
http://docs.toddish.co.uk/popup/demos/
Long story short, the popup plugin creates divs by default given the classes ".popup_back" and ".popup_cont".
I have another button I wish to press which should completely delete the added divs with those classes after they have been generated and added to the html. As if they never even existed. Surely this is possible?
I have tried running a function which simply runs:
$(".popup_back").remove();
$(".popup_cont").remove();
As shown in this example:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_dom_remove
Unfortunately despite the code running, the actual divs are never deleted as required.
Any ideas? I am new to this kind of thing and have googled around and read a lot about DOM etc but am yet to crack it.
Thanks
EDIT:
In reply to the comments:
The Javascript:
function removePopups() { // This function is called to remove the popups.
console.log("removing...");
$(".popup_back").remove();
$(".popup_cont").remove();
}
function func(url) { // url is the url of the image to be displayed within the popup.
removePopups(); // As soon as the function casillas is called, removePopups is used to remove any existing instances of the divs.
$('a.theimage').popup({ // This is where the Popup plugin is utilised.
content : $(url),
type : 'html'
});
}
The HTML:
<a class="theimage" onclick="func('image/image1.jpg')" href="#" >
Long story short, an image is displayed in the popup.
I think the issue is that the popup plugin runs due to the class but the function func is never actually run when the click occurs. However simultaneously "removing..." still prints out in the console which tells me that the function IS being executed. The problem is I want the popup plugin to run together with the javascript function. Is there a solution for this conflict?
Your implementation should really be as simple as this:
<a class="theimage" href="#" >Open</a>
Bind the popup creation to your popup link:
$('a.theimage').popup({
content : 'image/image1.jpg',
type : 'html'
});
I'm speculating here, but what might be happening is that you're invoking the popup twice by binding the popup() call to a click handler in your markup. The popup plugin already binds the popup creation to a click event.
View working demo. Note the 3 external resource: the popup CSS, the popup JS, and the jQuery JS.

How do I discover which function is called when I press a button?

I'm stuck modifying someone else's source code, and unfortunately it's very strongly NOT documented.
I'm trying to figure out which function is called when I press a button as part of an effort to trace the current bug to it's source, and I"m having no luck. From what I can tell, the function is dynamically added to the button after it's generated. As a result, there's no onlick="" for me to examine, and I can't find anything else in my debug panel that helps.
While I prefer Chrome, I'm more than willing to boot up in a different browser if I have to.
In Chrome, type the following in your URL bar after the page has been fully loaded (don't forget to change the button class):
var b = document.getElementsByClassName("ButtonClass"); alert(b[0].onclick);
or you can try (make the appropriate changes for the correct button id):
var b = document.getElementById("ButtonID"); alert(b.onclick);
This should alert the function name/code snippet in a message box.
After having the function name or the code snippet you just gotta perform a seach through the .js files for the snippet/function name.
Hope it helps!
Open page with your browser's JavaScript debugger open
Click "Break all" or equivalent
Click button you wish to investigate (may require some finesse if mouseovering page elements causes events to be fired. If timeouts or intervals occur in the page, they may get in the way, too.)
Inspect the buttons markup and look at its class / id. Use that class or id and search the JavaScript, it's quite likely that the previous developer has done something like
document.getElementById('someId').onclick = someFunction...;
or
document.getElementById('someId').addEventListener("click", doSomething, false);
You can add a trace variable to each function. Use console.log() to view the trace results.
Like so:
function blah(trace) {
console.log('blah called from: '+trace);
}
(to view the results, you have to open the developer console)

Categories