Changing html content using javascript[Theory] - javascript

Suppose i open a website say stackoverflow.com now it contains a lot of html content,texts,spans etc .How will i be able to change the content of html automatically using script(jquery) if i know the classes and id of the elements of html.
say a webpage has these elements
<span class="a">Great</span>
Now i want to change it when i open the webpage to
<span class="a">Not Great</span>
Since i have no control on servers or resources of files i can change it from dev but that is manually . how to do it automatically ?

You want to create a Bookmarklet.
A bookmark can be more than just a URL -- they can also be snippets of injectable JavaScript.
Bookmarklets can be used to alter or modify any page that you're viewing on the web. They can add additional information about the page, aide the user in reading it, or perform some automated action in a web app.
javascript:(function(){
if (window.jQuery) alert("jQuery is present");
else alert("jQuery is NOT present");
})();
Just create a new bookmark, and paste the above as its URL. Click the bookmarklet to execute it on any page (to see if jQuery is present).
You can also use the bookmarklet code as an <a> tag's [href] attribute -- then the link can be right-clicked and bookmarked from there (the easiest way to get a user to install your bookmarklet).
My favorite bookmarklet is H5o, the HTML5 Document Outliner! Use it to check any web page's document outline structure, highly important for good SEO!
H5o Bookmarklet Installation Page
H5o on Google Code

Very simple. You can use:
$(document).ready(function(){
$(".a").text("Not Great");
});

Given your example...
jQuery(".a").text("Not Great");
Or, if you want to include tags:
jQuery(".a").html("<strong>Not Great</strong>");

Related

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

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>

Trace URL's that link to my iframe/widget

I have created a widget.html page with, for example, a "Powered by Example.com" box/widget. And I have an HTML iframe that links to that specific page (widget.html) on my site.
<iframe src="http://example.com/widget.html"></iframe>
I share that iframe code with website owners who want to use my widget on their sites.
I want to be able to see every single site that uses my iframe. I would prefer a code that creates a txt file or even a MySQL Table with all websites URLs that use my widget on their websites.
I basically want to track the sites that use my widget as an iframe . How do I do that? With Javascript? PHP? MySQL?
P.S. I'm not sure if an iframe is the best way to link widgets off my site, but I'm open for your suggestions. Thanks in advance.
use jquery
then load a request page throgh jquery like : $("#div1").load("demo_test.txt");
and send a request uri parameter to it
you will find the current url using the widget and alos you can get the parameter

Linking to the end of another page in which i have no access to the source of

The website i'm trying to link to is pretty much a text document (see below), i'm trying to link to the last line preferable, highlighting it would be ideal but a link to the end of the page would work.
I've tried various code snippets, but as i have no access to the code of the page i cannot create anchor in the target page and link directly to that.
if i can get the following code to run on the page once i have navigated to it, i believe that would solve the problem, but my JS knowledge does not extend that far
window.onload=toBottom;
function toBottom()
{
alert("Scrolling to bottom ...");
window.scrollTo(0, document.body.scrollHeight);
}
i am linking using the following code
`— Alan Turing `
http://www.loebner.net/Prizef/TuringArticle.html
I would deeplink and find an ID on the remote page and link directly to that so for example
www.loebner.net/Prizef/TuringArticle.html#ELEMENTID
However if the page does not have an element at the bottom with an ID then might be a problem, do you have access to that page to add an ID?
Cleanest solution was contacting the site administrator of the site and setting up a mirror on my server of the original file and adding an #ID to the element i wanted to deeplink to and linking to the #ID from within my webpage
href="<c:url value="loebner#ID"/>"

load external site and change its visualization

I'm trying to create a web page able to change a site visualization (.css or / and .js) in order to recreate the same live change capability offred by Firebug for Firefox or the Inspector of Chrome.
Here an image to better explain my task:
I have been able to visualize the other site inside my page using the iframe, but unfortunately it is not possible to change its visualization and access its elements due to the "same origin policy".
Is there a way to do this using the iframe or loading the external site inside another element?
Update:
Considering the answers the options should be:
create a php proxy page to load the target site and change visualization on it.
create a browser extention.
I've tried the first, even if it requires to install a web server (xampp), with a simple page calling the function file_get_contents('http://www.site.com');
The page is loaded but unfortunately missed some elements (like images) and it is only a static copy; it is not possible to go further in the site navigation.
Update 2:
Load the entire page via javascript could be the better solution (I don't konw how) if it is possible to live change the code but what about the possibility to interact with this "page copy" and transfer the interaction to the original one?
Scheme:
Explanation:
I've noticed Firebug extention can select and live edit any page element, even if they belong to the iframe which loads an external domain page.
What I'm looking for is a way to act like Firebug, get an element and change its style.
I'm trying to load the site into the iframe beacuse I wanted to create a toolbar above it to select my "visualization styles"; for example a button to makes titles bigger and red.
Anyway I'm open to any other methods suggestions.
Update 3:
I have found an extention for both FireFox and Chrome which is really close to my aim: "Stylish"
This add on allows to live change any site css proprerty and save it in order to reload them every time you'll visit the page.
Now my question is: How can I do the same creating a dedicated page to load and change visualization of a specific site?
FINAL EDIT:
In order to continue this question with a more relevant arguments I decided to ask a new one: create a php proxy page
No. Your solutions may be
to let your own site act as proxy so the same origin policy isn't triggered
to build an extension, which will be browser dependent (Firefox or Chrome) and which will require authorization and installation
I'm not sure if I understand what you want very well, but my feeling to ''trick'' this easier would probably to give very specific height and width to your first site (the iframe) and do a jQuery condition
If ($('body').width() == 500 && $('body').height() == 400 {
$('body').addClass('isiFrame');
}
Then, you only have to do your css .isiFrame .myCoolDivs {....}
You might have to use it on a document ready also, but that could be one way to trick it and since you're not doing it on resize (exepect if somebody's having his screen at this exact width and height at start)
The safer way would probably to create a master session using PHP but I cannot give you an example since it've been to long and echo the body class if the master_session or variable is equal to true
Hope it helped!
If you try to fight Same_origin_policy and try to fight it I am sure you won't get much success their.
Server Side
I would suggest you Handle this on server-side, grab the web-page and apply whatever styling and scripts you want, should be very easy!!
If you use Ruby on rails - Nokogiri gem can help you to parse html. And you can use standard library to 'get' a webpage.
Client Side
If you want to do this on client side, you need to write some jquery/javascript code, you can take following steps:
Get the webpage you want to display.
Grab the element's which include js/css files, remove them and your own.
Display the page in new Iframe present in your page.

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.

Categories

Resources