How to automatically run custom JavaScript code when loading a webpage? - javascript

Now I have a block of JavaScript code to change the display of a webpage, say to highlight some data so that when I read the webpage I can easily find them.
The code is super simple, you can just imagine it as
document.getElementById(index).classList.add("highlight")
index is used to find the content needing to be changed. I will append highlight class to the class attribute of found content so that the display would be changed (just for illustration of the purpose)
Now the problem is, whenever I open the webpage, I need to copy and paste this code to console in Chrome and run it, which is troublesome. So I am wondering whether it is possible that the Chrome will run this script automatically when I load the webpage. Say for example, I have a hyperlink directs to the webpage and when I click the hyperlink, the script will be run and the display of the webpage will be changed.
Tampermonkey is not really helpful in my case. I have another method to generate the JavaScript for different webpages so the script I want to run will change when I load different webpages.

There are some tools for this purpose you can use:
TamperMonkey
Tampermonkey is the most popular userscript manager, with over 10 million users.
RunJS
RunJS is a developer tool that allows users to debug pages by running specified JS across all page loads.

I highly recommend User CSS and Javascript chrome extension. I have been using it for years with no issues whatsoever. In fact, I have customized the vast majority of the websites I use on a daily basis using it!

You could actually use a bookmarklet which should simplify the process. https://gist.github.com/caseywatts/c0cec1f89ccdb8b469b1. If you want to fully automate it however you need to create a plugin

yes there is, try following code.
<script>
window.onload = function(){
alert("ready");
// place your code here ...
}
</script>
or just write your code at the bottom of file, like this
<html>
<head></head>
<body>
<!-- any html tags here -->
<script>
// any JS code here
</script>
</body>
</html>

Related

How do I parse an HTML Code which is generated via Java Script

My task at hand is to download a file through vba. The problem is, that the page is mostly generated via JavaScript. Sorry that i cannot just share the page with you, because I dont own it, but I will try to make things as clear as possible.
The HTML from the IE source viewer looks similar to this:
<head>
css stuff
jscript link
more jscript links
more css stuff
</head>
<body>
divs and links and so on
<div magic inside that div that shows on browser but not in source code></div>
</body>
I very much believe that the java script generates an iframe and fills it with html code.
Do you think that it is possible to retrieve the finished iframe from the java script? Because I can literally see the HTML code when i use the chrome DOM explorer, but I cannot fetch the HMTL data in vba. It drives me crazy that I dont understand this :D
Thank you for your time
What you have described looks like a typical DHTML that could be generated by JS after XHR request. So open the web page e. g. in Chrome, check the Network tab. After the target content has been generated on the page, you will see all requests on the tab, examine them, usually all the data you need to retrieve are shown there (note that some conversion of the data may be necessary).  If you find it then you may just do a XHR with the same parameters to retrieve result. Or another way, you can retrieve the generated HTML content accessing DOM, if the iframe is same origin, as it was mentioned above.

Showing a demo of my CSS on any website

I have developed a small component which can be put in to any website. Now, I want to develop a code that could demonstrate how would my component look like on any website.
So, the person would come to my page and put in his URL and then my code should embed my custom JS/CSS in to the downloaded HTML and display it. Something like this.
Here, like the feedback tab, I want to show my component any where on that page.
Try a bookmarklet.
Create a piece of javascript that adds your code into the page such as the following:
javascript:(function(){var%20script=document.createElement('script');script.src='http://www.example.org/js/example.js';document.getElementsByTagName('head')[0].appendChild(script);})()
Add it as the href of a link like so:
Link Text Here
Tell your users to drag the link to their bookmark toolbar and click on it on different websites to try your code out.
Some examples: http://www.reclaimprivacy.org/, http://www.readability.com/bookmarklets
In the example you linked, they are requesting the page specified in the url querystring parameter on the server, and then doing more or less the following steps:
In the <head> tag they are adding a <base href="url" /> tag to the document. The base tag will make any relative links in the document treat the value in the href attribute as their root. This is how they are getting around broken css / images. (The base tag is supported by all browsers)
At the end of the document (IE the </body> tag) they are injecting the javascript that runs their demos.
They serve the modified HTML requested to the browser.
All of this is pretty straight forward in implementation. You could use regular expressions to match the <head> and </body> tags for steps 1 and 2 respectively. Depending on the server platform how you actually request the page will vary, but here are some links to get you started:
C# - HttpWebRequest object documentation
PHP - HttpRequest::send
Nathan's answer is the closest to how we have done the demo feature at WebEngage. To make such a demo functional, you'll need to create a Javascript widget that can be embedded on third party sites. syserr0r's answer on creating a bookmarklet is the simplest approach to do so. Our's is a JAVA backend and we use HttpClient to fetch the responses. As Nathan suggested, we parse the response, sanitize it and add our widget Javascript to the response. The widget JS code takes it on from there to render the Feedback tab and load a demo short survey.
Disclosure: I am a co-founder and ceo at WebEngage.
You can not do this with JQuery due to cross site scripting restrictions.
I suggest you write a PHP script that downloads the URL specified by the user and includes your widget code and then echo it back to the user.
I recommend using bookmarklets. I've made a bookmarklet generator for adding jQuery-enabled bookmarklets to a page to make development easier.
There's a caliper bookmarklet on the page that you can mess around with just to show an example of it working.
Full disclosure, this is something I've made, I'm not trying to be spammy as I think it's relevant: zbooks
You could make an iframe page, which loads their page in the iframe, and uses javascript to inject your code into the iframe.
Here is my approach...
http://jsfiddle.net/L2kEf/
html
<iframe src="http://www.bing.com"></iframe>
<div>I am div</div>
css
div { background: red; position: absolute; top: 20px; width: 100px; left:20px;}
iframe{width: 100%; height: 500px;}
you can add javascript/jquery too, so you could do something like,
jQuery //not 100% sure it would work coz of cross browser thingy, but you know, worth a try.
$('div').click(function (){
$('iframe').contents().html('changed');///
});
if this can't change any of the contents, you can display a dialog, to say it would normally work if it was in your website, then use #syserr0r approach for bookmarked users, for better results, since you are offering this kinda services, to developers, im sure they would know about bookmarking, my approach would be rarely used :) so hope it helps.
I had a problem of a similiar nature, and the main obstacle is the cross-domain policy.
You have to ask the user to put your code in a <script src="..."> or create a proxy solution that would add your code for them.
I went for the proxy and here are my observations:
it's easy to create a basic proxy in php - there are some php proxies on sourceforge and Ben Alman has created a simple php proxy for AJAX. Based on those I was able to create a php proxy altering the content properly in one day.
after that I spent a lot of time making it work with more and more sites with issues. You can never create a perfect proxy.
As an alternative (sa long as you are non-commercial) you can use http://www.jmarshall.com/tools/cgiproxy/ and put the site in an iframe and then do whatever you want to do with the iframes document, as it's in your domain thanks to the proxy. You can access iframeDOMnode.contentWindow.document then, etc.
You can create a Crossrider extension which your users can download.
Then simply add this to your App/Extension code:
appAPI.dom.addRemoteJS("http://yourdomain.com/file.js")
Your users can then download the extension (it works cross-browser for Internet Explorer, Chrome and Firefox) and it will load your JS code on every page load.
You can get an approximation of what it will look like using a iframe. Take a look at that link for an example.
http://jsfiddle.net/jzaun/5PjRy/
The issue with this appoch is that you can't move your DIV(s) when the page scrolls, they are in effect just floating over the iframe. There is no way around this as cross-domain scripting wont let you access the iframe's document to monitor scroll events.
The only other option you have for a better fitting example would be to load the page from the server side in whatever scripting language you are using and load that into the iframe (or into a div, etc.) and you can use javascript all you want as the page is coming from your domain.
For your example of what will your widget look like I imagine floating your DIV(s) over an iframe would give enough of an idea.
Please note the example you gave is using the server side method, not the iframe method.
I agree with the bookmarklet strategy.
I'm a fan of http://bookmarklets.heroku.com/, which lets you generate bookmarklets easily, inject jQuery, etc.

Javascript to reload page with javascript disabled

I am interacting with a webpage that I need to have java scripting alternatively disabled and then enabled.
I can't change the scripting setting in the browser to disable scripting since some of the website requires scripting be enable to work properly.
The program I am using allows me to execute a javascript but I can't figure out how to code a script that load a page with javascript disabled.
Any ideas how I can run a javascript to disable scripts on the page?
Thanks for all the feedback - A little more background might help.
I am using a program to create a bot that automates some of my repetitive tasks. The problem is that my program doesn't recognize the links generated by java scripting on the first two pages of the process so I have to have scripting disabled in my browser. Unfortunately on the last and final page of the process scripting is required to render a menu.
I am have request with their development team to change this final page so its viewable without scripts but in the meantime I've still got this problem.
I believe I'll be able to make this work by opening a new browser window, executing the window onload script for the first two steps then going back to a regular window for the final step. I'll let you know if it works.
And yes this is for a personal project and the site owners are aware of my attempts to automate their pages with my software.
You can't disable scripts using javascript.
Disabling javascript is something that is done within the browser configuration.
If your script is run outside the browser, you may be able to point it at 2 different browsers, one that has javascript enabled and one that doesn't.
Alternatively, some browsers (Firefox) have the notion of "Profiles" that you can start directly - so you could have one profile with javascript enabled and one without it.
The only way you could force a reload without Javascript is via a meta-refresh in the page's <head> block:
<meta http-equiv="refresh" content="600;url=http://address.to.your/page" />
or output some text to tell people to "click here to refresh".
Basically you're asking "how can I drive my car somewhere after I remove the engine".
You could look into an add-on for your browser that disables scripts.
Particularly one that can disable them on only a few pages per website, and not the whole site.
...with great difficulty!
However, if you can put this right at the top of the document (preferably inside an if statement acting upon whatever trigger you're using to enable/disable JavaScript):
<script>
window.onload = function()
{
var contents = document.getElementsByTagName('XMP')[0].innerHTML;
contents = contents.replace(/<script/gi, '<xscript');
contents = contents.replace(/<\/script/gi, '</xscript');
contents = contents.replace(/ on([a-z]+=)/gi, ' *$1');
document.open();
document.write(contents);
document.close();
}
document.write("<xmp>");
</script>
That just might do the job. Except for JavaScript running in IFRAMES and things like that. And except for the unlikely scenario that you're actually using the lesser-spotted XMP element somewhere within your pages.
Not working in Safari. Is this just for your own personal use?

AddThis share button wont work in DotNetNuke

For some reason when I add a HTML module (well the default module added to DNN 5.4) and then add the "AddThis" javascript. While the button shows up clicking on it opens up a new page rather than showing an iframe modal message or on hover a list of popular social media networks to share the page with. Wonder what would be the easiest way to resolve this and why this happens?
This is not a complete answer, but to me it sounds like the AddThis javascript code is never loaded by the browser. When viewing the web page that doesn't workg, open the HTML source and look for the AddThis script tag. It probably should look something like this:
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=..."></script>
If you can not find it, then there is something to work on. If you find it, try to open the URL in your browser and see if you get the javascript.
Otherwise: as always, FireBug (or the tools in IE8) is your friend.
Try copying the addthis script reference and pasting it to the page header tags:
http://s7.addthis.com/js/250/addthis_widget.js#pub=AddThis

Programmatically remove <script src="/unwanted.js".. /> reference

I have partial control of a web page where by I can enter snippets of code at various places, but I cannot remove any preexisting code.
There is a script reference midway through the page
<script src="/unwanted.js" type="text/javascript"></script>
but I do not want the script to load. I cannot access the unwanted.js file. Is there anyway I can use javascript executing above this refernce to cause the unwanted.js file not to load?
Edit: To answer the comments asking what and why:
I'm setting up a Stack Exchange site and the WMD* js file loads halfway down the page. SE will allow you to insert HTML in various parts of the page - so you can have your custom header and footer etc. I want to override the standard WMD code with my own version of it.
I can get around the problem by just loading javascript after the original WMD script loads and replacing the functions with my own - but it would be nice not to have such a large chunk of JS load needlessly.
*WMD = the mark down editor used here at SO, and on the SE sites.
In short, you can't. Even if there is a hack, it would heavily depend on the way browsers parse the HTML and load the scripts and hence wouldn't be compatible with all browsers.
Please tell us exactly what you can and cannot do, and (preferably; this sounds fascinating) why.
If you can, try inserting <!-- before the script include and --> afterwards to comment it out.
Alternatively, look through the script file and see if there's any way that you could break it or nullify its effects. (this would depend entirely on the script itself; if you want more specific advice, please post more details, or preferably, the script itself.
Could you start an HTML comment above it and end below it in another block?
What does the contents of unwanted.js look like?
You can remove a script from the DOM after it is called by using something simple such as:
s = document.getElementById ("my_script");
s.parentNode.removeChild(s);
This will stop all functions of the script but will not take it out of user's cache. However like you wanted it can't be used.
Basically you can't unless you have access to the page content before you render it.
If you can manipulate the HTML before you send it off to the browser, you can write a regular expression that will match the desired piece of code, and remove it.

Categories

Resources