execute onChange when a certain condition/event is detected jQuery - javascript

alright.. i have an input box that captures paste event and checks if the pasted text/string is a youtube url. if yes, it will forward data to some PHP to process..
the result json data is being displayed here $('.printdata').append(response);
concerns:
what i didn't have in my code, is to recognize if the whole text or
the youtube link is removed/cut/deleted. it should also remove the
displayed data.
accept the first youtube URL, if multiple youtube URL is found, send the first link to PHP, then ignore the others, just display it as text.
my workaround
what im thinking (tho not sure) is to put some onchange() event
somewhere to recognize $("$input") element is being changed.
accept only a single paste event and ignore if paste() is repeated. -not sure if this is the right approach.
http://jsfiddle.net/8Pvr4/4/
to test what im trying to explain, input any youtube url in the textfield, and it should display something.
then remove the url, the data remains. OR add another URL consecutively. the resulting data will stack.
$(document).ready(function() {
//some regex
$("#input").bind('paste', function(e) {
var val = undefined;
//get pasted data
if(window.clipboardData && window.clipboardData.getData) {
val = window.clipboardData.getData('Text');
} else if (e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData){
val = e.originalEvent.clipboardData.getData('text/plain');
}
//check for youtube URL
if (youtube.test(val)) {
var yurl = val.match(youtube)[0];
$.post("youtubejson.php?url="+ yurl, {
}, function(response){
$('.printdata').append(response);
});
}
});

I'm not sure i understand your question properly, but i guess your result is stacking and not getting replaced, you can use .html(response) instead of .append(response) to stop stacking.

Related

JavaScript browser navbar event

I want to prevent users to navigate to URL´s that are not accessed through html element. Example:
Actually navigating on: myweb.com/news
And I want to navigate to myweb.com/news?article_id=10 by writing this in the browser navigation bar to avoid pressing any element (like <a>).
When the user writes myweb.com/news?article_id=10 in the browser url, at the moment he presses enter, the browser should not allow him to navigate to the url.
I have tried:
//This wont work since jquery does not support it
$(window.location.href).on('change', function() {
//Here check if href contains '?'
alert("Not allowed");
});
//Neither works, doesnt do anything
$(window).on('change', function() {
alert("Not allowed");
});
References:
there is something similar asked here On - window.location.hash - Change?, but im interested in the 'parameter' version of that question.
There are some known solutions :
) Each time a user click a link - you save the page value to a cookie.
Later , at the server- you check that interval ( value-1 ... value+1).
) You can also save to a hidden field and check that value in the server.
So let's say a user is on page 3. ( the server serve that page - so a cookie/hidden value with value 3 is exists)
now he tries to go to page 10 :
you - in the server side - reads the cookie + requested Page number. if the interval is bigger than 1 - then you deny that request.
Try adding an event listener:
window.addEventListener('popstate', function(event)
{
var location = document.location;
var state = JSON.stringify(event.state);
});
To check the URL, The best thing would be to match it against a regex like:
if (url.match(/\?./)) {
// do not allow access
}
You might need to extend this, depending on other URL's that you need to forbid access to.

How to determine the http-request's location/origin (address-bar)?

So I'm trying to redirect the browser to another webpage when the page he is attempting to load matches my conditions (regex). Currently it looks like this: (came up with it here)
function listener(event) {
var channel = event.subject.QueryInterface(Ci.nsIHttpChannel);
var url = event.subject.URI.spec;
if (isToBeRedirected(url)) {
// replace url
}
}
exports.main = function() {
events.on("http-on-modify-request", listener);
}
But the problem is, that this will also replace urls to images for example, which are embedded in the page. My question would be, is there a way of varyfying that the http request is made by typing in a url or clicking a link to a page? So simply everytime a url shows up in the address-bar.
I thought about reading the url of the current tab and comparing it to the request url, but I wasnt able to find out exactly how yet.
I have an idea.
If you do console.log(Ci.nsIHttpChannel) you see it has a bunch of flags, see img at bottom.
So I'm thinking test if it's the main load, meaning its not in a sub frame, but its the whole document of the tab by testing for flag of Ci.nsIHttpChannel.LOAD_INITIAL_DOCUMENT_URI. If its the whole document, its likely from a link, or url bar, or search bar.
So try this:
function listener(event) {
var channel = event.subject.QueryInterface(Ci.nsIHttpChannel);
var url = event.subject.URI.spec;
if (channel.loadFlags & Ci.nsIHttpChannel.LOAD_INITIAL_DOCUMENT_URI) {
//the whole document of the tab is changing
if (isToBeRedirected(url)) {
// replace url
}
}
}
exports.main = function() {
events.on("http-on-modify-request", listener);
}
My other idea, is if you want only url bar changes. Than add an event listener to change of the url bar value. And after change if user hits enter or clicks go, then it register the observer. Then after testing for Ci.nsIHttpChannel.LOAD_INITIAL_DOCUMENT_URI than unregister the observer.

Use javascript to set the image shown by Facebook sharer

I'm trying to dynamically set the thumbnail shown when sharing to Facebook using javascript. I tried adding the meta tag "og:image" to the page (it's a JSP) and that works, but what I want to do now is to replace such image with another one dynamically loaded by javascript.
Basically, the page is calling an API upon loading, using javascript, and retrieves a list of images. I want to use one of those as the thumbnail.
I tried using javascript to replace the content of the meta tag, but Facebook doesn't seem to care abou t it (it does change if I check with my browser).
Is it possible to do this?
Thanks in advance!
Here is a function I used to extract the image url from a flash object tag's flashvars parameter, and then assign it to a meta tag by using jquery:
$(window).load(function(){
//Use $(window).load() instead of $(document).ready(), so that the flash code has loaded and you have all the html you need process with javascript already in place when you start processing.
var stringToExtractFrom = $('param[name="flashvars"]').attr('value');
//Get the flashvars parameter value which we'll use to extract the preview image url from.
var pos = stringToExtractFrom.indexOf("&");
//Search for the position ampersand symbols which surround the image url.
var stringToUse;
//The final string we'll use.
var startOfImageSrc = null;
//The first position where we discover the ampersand
var endOfImageSrc;
//The second position where we discover the ampersand
var lengthToSubstract
//How many symbols to chop off the flashvars value.
while(pos > -1) {
if(startOfImageSrc == null){
startOfImageSrc = pos;
}
else {
endOfImageSrc = pos;
lengthToSubstract = endOfImageSrc - startOfImageSrc;
}
pos = stringToExtractFrom.indexOf("&", pos+1);
}
stringToUse = stringToExtractFrom.substr(startOfImageSrc+7, lengthToSubstract-7);
$('meta[property="og:image"]').attr('content', stringToUse); });
Facebook robot never runs a java script code
but why you don't try to set og tags in in server-side ?

How to use javascript to get information from the content of another page (same domain)?

Let's say I have a web page (/index.html) that contains the following
<li>
<div>item1</div>
details
</li>
and I would like to have some javascript on /index.html to load that
/details/item1.html page and extract some information from that page.
The page /details/item1.html might contain things like
<div id="some_id">
picture
map
</div>
My task is to write a greasemonkey script, so changing anything serverside is not an option.
To summarize, javascript is running on /index.html and I would
like to have the javascript code to add some information on /index.html
extracted from both /index.html and /details/item1.html.
My question is how to fetch information from /details/item1.html.
I currently have written code to extract the link (e.g. /details/item1.html)
and pass this on to a method that should extract the wanted information (at first
just .innerHTML from the some_id div is ok, I can process futher later).
The following is my current attempt, but it does not work. Any suggestions?
function get_information(link)
{
var obj = document.createElement('object');
obj.data = link;
document.getElementsByTagName('body')[0].appendChild(obj)
var some_id = document.getElementById('some_id');
if (! some_id) {
alert("some_id == NULL");
return "";
}
return some_id.innerHTML;
}
First:
function get_information(link, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", link, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
xhr.send(null);
}
then
get_information("/details/item1.html", function(text) {
var div = document.createElement("div");
div.innerHTML = text;
// Do something with the div here, like inserting it into the page
});
I have not tested any of this - off the top of my head. YMMV
As only one page exists in the client (browser) at a time and all other (virtual/possible) pages are on the server, how will you get information from another page using JavaScript as you will have to interact with the server at some point to retrieve the second page?
If you can, integrate some AJAX-request to load the second page (and parse it), but if that's not an option, I'd say you'll have to load all pages that you want to extract information from at the same time, hide the bits you don't want to show (in hidden DIVs?) and then get your index (or whoever controls the view) to retrieve the needed information from there ... even though that sounds pretty creepy ;)
You can load the page in a hidden iframe and use normal DOM manipulation to extract the results, or get the text of the page via AJAX, grab the part between <body...>...</body>¨ and temporarily inject it into a div. (The second might fail for some exotic elements like ins.) I would expect Greasemonkey to have more powerful functions than normal Javascript for stuff like that, though - it might be worth to thumb through the documentation.

JavaScript: Show / Hide <DIV> based on URL string

I need to show a DIV on two pages (URL's) but not on the others.
(I have jQuery on the pages if that helps.). I'm a complete noob so all help is very much appreciate. Thank's!
Case (1) where I want to show the DIV:
On the start page, when the web browser address field reads 'www.mydomin.com'
The start page is PHP so I guess the full URL is 'www.mydomin.com/index.php'
Case (2):
'www.mydomin.com/index.php?option=com_myblog&title.html&Itemid=1&lang=en'
WHERE this part is alway the same
'www.mydomin.com/index.php?option=com_myblog&'
AND this part is always unique
'title.html&Itemid=1&lang=en
Example
if (url == 'www.mydomin.com' or 'www.mydomin.com/index.php?option=com_myblog&') {
do this
xxxxxxxx
else
nothing
This should work, if I understand the question correctly
var url = document.location.href;
if (url.indexOf('www.mydomin.com/index.php?option=com_myblog&') >= 0) {
$('#div_id').hide();
} else {
$('#div_id').show();
}
But really, if you use PHP anyway, you should figure out how to not render the div in the first place.
You can parse the query string and show/hide the div based on the result.
I also think it should be handled from PHP code instead from JavaScript. And div should not be rendered in first place.
You can target a specific query parameter of the URL using window.location.search. Using the below code, you can find an exact match anddisplay/hide the HTML element:
var firstURLParam = window.location.search.substring(1).split('&')[0];
var datGuiEle = document.getElementById("elemID");
if(firstURLParam == "debug"){
datGuiEle.style.display = "block";
}
else {
datGuiEle.style.display = "none";
}

Categories