Javascript: How may I call a function of an external website? - javascript

I would like to write a simple script to open a Website and call a function that is part of a linked .js-file.
To be more precise, I want to open a SharePoint, invoke the function that is used to open the folder in windows explorer and close the website again.
For some reason, I may not open the folder directly in explorer unless I had it done this way at least once during the active windows session...
How may I do this?
So far, I tried the following:
var IE = new ActiveXObject("InternetExplorer.Application");
var WSH = new ActiveXObject("WScript.Shell");
IE.visible = true;
IE.navigate("https://mysharepoint.com/Folder");
WSH.PopUp("Click to fire function");
//the following line throws an error, because the function is unknown...
IE.Document.defaultView.setTimeout(NavigateHttpFolder, 0, "https://mysharepoint.com/Folder", "_blank");
//the following line does not throw an error, but nothing happens either..
IE.Document.defaultView.setTimeout(function(){NavigateHttpFolder("https://mysharepoint.com/Folder", "_blank");}, 0);
However, when I open my Sharepoint and type the following line into the addressbar it does exactly what I want to achieve and it opens the folder...
javascript:NavigateHttpFolder("https://mysharepoint.com/Folder", "_blank");
Could you please help me? I simply cannot find a way to get this to work.
UPDATE: Now it worked suddenly! I tried it the following way before but it didn't do anything until now (???)...
IE.Navigate('javascript:NavigateHttpFolder("https://mysharepoint.com/Folder", "_blank");');

You can include script with path to external website
<script type="text/javascript" src="http://www.external.com/script.js"></script>

Related

Cannot find source of javascript function call

Ok, so I need to find the source code of a particular javascript function on a website. (The specifics do not really matter unless there is no way to do what it is that I am asking)
I can see the function call in a link of html code
onclick="inbox.sendMessage();"
I know that the function does work because if I use a plugin a can call the function on that page, however, I have searched every .js file is referenced in that page, and none of them contain a function called sendMessage.
What I am asking is, is there a way to follow the code back to the source, perhaps if there was a way to debug the html and break when the onclick is triggered and then step into the function to see its source, but I do not know how I can do that or if it is even possible. Any help will be greatly appreciated, Thanks.
I guess you could do :
inbox.sendMessage
In the webconsole. (the function name without the parenthesis)
It will print out the source code of the function.
I usually use Opera, and in that at least this is what I do:
Open Opera Dragonfly (Ctrl + Shift + I).
Click on the HTML tag with the onclick handler.
Go to the listeners tab in the right hand side column.
See the listener for the click event. It shows you the file and line number.
sendMessage could be declared as:
var inbox{
sendMesssage:function(){
}
}
//or
function inbox(){
this.sendMessage=function(){
}
}
// or
inbox.sendMessage=function(){}
// or ...
So looking for "sendMessage(" or "function sendMessage" will not find you anything.
In chrome, Internet Explorer and Firefox (with firebug) you can hit F12 and go to debug, there you can check the scripts that have been loaded as there might have been scripts loaded dynamically.
#!/usr/bin/env ruby
Dir::glob("*").each do |name|
lineCount = 1
File.open(name, "r").each do |line|
puts "\nFile name: " + name + "\nline: " + lineCount.to_s if line =~ /inbox.sendMessage/ && name != "findfunction.rb"
lineCount += 1
end
end
Wrote a quick ruby script to help you out. To execute, first make sure you have a ruby interpreter on your machine then place the script in the directory with all your relevant files. load up a command line terminal, navigate to said directory and type "ruby findfunction.rb".
It will tell you all instances (files + line number) of "inbox.sendMessage".

How to update user script in greasemonkey

I have an issue with Greasemonkey, it doesn't update my script automatically (probably because we don't want to add it to its UserScripts root, and it seems in this case it doesn't update it)...
anyway, I was adding a piece of code (main idea from here) to my script to check the script version inside the script and let user know if there is a new version available, and as if user wants to update it, if so it should open a new window/tab for script url (that it should trigger Greasemonkey to install it)... this is my senario, and it works perfect up to the point that it should open a new window/tab...
here you can see the function I'm using:
function checkForUpdate(in_vid){
var plugin_url = 'https://MyWebSiteURL/MonaTest.user.js?'+new Date().getTime();
if ((parseInt(GM_getValue('SUC_last_update', '0')) + 86400000 <= (new Date().getTime()))){
try {
GM_xmlhttpRequest( {
method: 'GET',
url: plugin_url,
headers: {'Cache-Control': 'no-cache'},
onload: function(resp){
var local_version, remote_version, rt, script_name;
rt=resp.responseText;
GM_setValue('SUC_last_update', new Date().getTime()+'');
remote_version = parseFloat(/#version\s*(.*?)\s*$/m.exec(rt)[1]);
local_version = parseFloat(GM_getValue('SUC_current_version', '-1'));
if(local_version!=-1){
script_name = (/#name\s*(.*?)\s*$/m.exec(rt))[1];
GM_setValue('SUC_target_script_name', script_name);
if (remote_version > local_version){
if(confirm('There is an update available for the Greasemonkey script "'+script_name+'."\nWould you like to install it now?')){
-------> GM_openInTab(plugin_url);
//window.open(plugin_url,'_blank')
//location.assign(plugin_url);
GM_setValue('SUC_current_version', remote_version);
}
}
else{
GM_log('No update is available for "'+script_name+'"');
}
}
else{
GM_setValue('SUC_current_version', remote_version+'');
}
}
});
}
catch (err){
GM_log('An error occurred while checking for updates:\n'+err);
}
}
}
I tried to use GM_openInTab, but it returns this error in the console:
Timestamp: 9/27/12 9:55:33 AM
Error: ReferenceError: GM_openInTab is not defined
Source File: file:///Users/Mona/Library/Application%20Support/Firefox/Profiles/tonwb5lg.default/gm_scripts/MonaTest/MonaTest.user.js
Line: 97
I couldn't find any reference to indicate that GM_openInTab doesn't support anymore!
I tried other solutions, using window.open and location.assign... both of them doesn't work because they shows the script source codes without triggering Greasemonkey to install it...
I don't know if there is a way to update script using this method...
I would appreciate if you share your knowledge and help me with my problem.
Thanks for your time!
P.S. My firefox version is 15.0.1, Greasemonkey version is 1.1
don't forget to #grant.
correct me if im wrong, but your script does not end with js.
var plugin_url = 'https://MyWebSiteURL/MonaTest.user.js?'+new Date().getTime();
try forcing the .js extension.
when i added the date to my script, GM stopped installing it.
remove the date at the end and give it a try.
one last thing: you're basing your script on a script from 2009. take a look at a new one, like this from 2011.

Javascript bookmarklet fails on certain sites, creates ghostly new <html> page

I noticed that my Javascript bookmarklet was failing on certain sites like Google Reader and Google search results pages (and randomly on some non-Google sites). Looking at the console, I could see that, for these pages, clicking the bookmarklet did not append elements to the head/body like it normally did, but created a new document that looked like this:
<html>
<head></head>
<body></body>
</html>
Even when I reduced my bookmarklet to javascript:alert(window.location.href); it would create this blank page and run the bookmarklet therein, so that the alert showed about:blank. On most sites, this blank page is not created and the correct location is shown.
Can someone explain this? Are these sites sandboxing externally run code as a safety measure?
UPDATE: I currently can't reproduce this on browsers other than Chrome 17.0.932.0 dev. Please let me know if anyone else can reproduce these results on Chrome or otherwise.
I think this is a bug in Google Chrome, I've filed it to their bug database: https://bugs.webkit.org/show_bug.cgi?id=72606
You need to ensure that the topmost code, i.e. the one right after javascript: does not return anything.
Usually this is done by wrapping everything in void():
javascript:void(alert(window.location.href));
It's very odd that it breaks with alert() though since the function itself doesn't return anything...
If a javascript: url returns a string it will be used to create a new document:
javascript:'foo bar baz';
This can be a tough issue to debug if you don't know to watch out for it. It can crop up if you use a function that returns a string or end your bookmarklet with a line that sets a string value:
javascript: a = prompt('foo bar baz'); b = a;
A simple solution is to use a closure:
javascript:(function(){ var a; a = prompt('foo bar baz'); window.b = a}());
An alternative is to end with void 0;
javascript: a = prompt('foo bar baz'); b = a; void 0;

How to debug Javascript registered with RegisterClientScriptBlock method

I have many existing scripts that I need to debug, all embededed from code behind.
I would prefer to use Visual Studio 2008 client side debbging features, but breakpoints can only be set inside the aspx file withing a script block.
The problem is I can't put a breakpoint on the scripts because they are all registered from the code behind file(not the aspx file). The scripts are added to the page using ClientScriptManager.RegisterClientScriptBlock Method (Type, String, String, Boolean)
Here is an example(it's not broke, just an example of how it's added to the page).
if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
{
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
cstext2.Append("Form1.Message.value='Text from client script.'} </");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
}
Is it possible to debug it without having to pull out each script in a test page?
Edit: thank you
You should add the debugger; directive in your code. Something like this:
cstext2.Append("<script type=\"text/javascript\"> function DoClick() {debugger;");
cstext2.Append("Form1.Message.value='Text from client script.'} </");
...
Also, you will have to adjust your IE as follows:
Tools->internet options->advanced. Make sure that “Disable Script Debugging (other)” and “Disable Script Debugging (Internet Explorer) are NOT checked.
Now, if the DoClick method is called, a special exception will be generated and IE will suggest you to run a new instance of VS where you will be able to debug the script.
I hope, this helps.

IE 6/7 Access Denied trying to access a popup window.document

I'm creating a popup window with no URL source using window.open(). I don't give it a URL because soon I'll want to post a form to it. However, in the meantime I'd like to display a short "Now loading..." message so the user isn't looking at a blank page for the 2-3 seconds it'll take the form post to go through.
I tried adding Javascript that just writes to the popup window's document. That worked great in Firefox and IE 8, but failed with an Access Denied message in IE 6 and 7. Anyone know of a way around this? I would love to be able to a) hard-code some HTML into window.open(), b) learn how to update the popup's DOM in this situation, or c) hear about anything anyone can think of.
Below is the code I'm using to spawn the window:
var wref = window.open("", winName, "toolbar=1,resizable=1,menubar=1,location=1,status=1,scrollbars=1,width=800,height=600");
if (wref != null) {
try {wref.opener = self;} catch (exc) {}
// while we wait for the handoff form post to go through, display a simple wait message
$j(wref.document.body).html('Now loading …'); // EPIC FAIL
wref.focus();
IE considers "about:blank" to be a insecure URL and it won't let you talk to it. I would create a "Now Loading..." static HTML file and open that instead.
Test
<script type="text/javascript">
function test() {
window.open('javascript:opener.write(window);', '_name', 'width=200,height=200');
}
function write(w) {
w.document.write("Hello, World.");
}
</script>
Works in IE 6, 7 & 8, Opera 9.6, Firefox 2 & 3.
Does not work in Safari for Windows 3 & 4 or Google Chrome.
When it does work, it results in a pretty ugly URL in the Location box.
If the browser support listed above is acceptable, you can use the solution provided, otherwise I'd do what David said and window.open('Loading.htm' ...) where Loading.htm contains whatever content you want to display (you should probably keep it lightweight otherwise it might take longer to load and render than the form will to POST).
Also note that the winName you supply in IE must NOT have spaces... if so it will fail.
Another workaround is to open an empty "blank.htm" file on your site, then do the document.open() to access it

Categories

Resources