Adding an extra button in facebook post using google chrome extension - javascript

I was successful to track all "uiStreamSource" that holds the link associated with each facebook post (status, image, etc) to add one extra button next to the date to do some other tasks using google chrome extensions. This button does a predefined job which not important to mention in this context.
I wrote this content script:
contentscript.js
var nodeslist=document.getElementsByClassName("uiStreamSource");
alert(nodeslist.length);
Each time a facebook page is loaded, the alert shows me 10 detected classes (i.e., 10 posts). But when I scroll down, new posts show up and this code fails to detect them. Since I need to update all uiStreamSource nodes in all posts, how can I solve this?
UPDATE
I tried this code in contentscript.js:
load();
document.addEventListener("DOMNodeInsertedIntoDocument", load, false);
function load(){
var nodeslist=document.getElementsByClassName("uiStreamSource");
alert(nodeslist.length);
}
The first time it runs, I get the correct number of the current nodes (current facebook posts) but once I scroll down and more posts are fetched, the alert shows up indicating that load function is called but the number of nodes printed is 0. Why is that?
Thanks on advance.

You can add a DOMNodeInserted event and check if the element that is going to be inserted is a post by checking its classes.
Or an easy solution is to use the jcade plugin. It can call a callback function when an element with specified selector is inserted.

Listen to the scroll event and add any new posts to nodeslist. You could use setInterval as well to catch any posts that are added when the user is not scrolling.

Related

Stop Safari extension from caching messages

I'm having problems with creating a safari extension that has been causing me headaches.
The problem is this: I have created an extension that gets images from a web page using an injected script. I have a function in the popover that displays the web images and allows the user to click and send the selected image to a backend. This all goes through the global page which handles signals and messages. The scenario is this:
When the popover opens, it sends a signal to the global page to initiate the response (image URLs) from the injected script.
When the global page gets the message from the injected script, it calls the function in the popover passing in the data from the injected script as an argument.
The popover shows all images returned from the global page via the injected script.
The problem is that every time I open the popover, it appends the images from the last call instead of giving a fresh list of images. For instance, on first popover open, I get one image (assuming the page has only one image). If I close the popover and open it again, I get two of the same image. If I close and open the popover a third time, it appends the first image with the one from the second time and gives me 3 of the same image. On the fourth open of the popover I get 1 + 1 + 1 + 1, so 4 images. So it seems to be appending the messages and not giving me a fresh message every time.
My question is: how can I destroy the messages that are being cached after each popover closes? I hope I am being clear. Perhaps something else is happening with my code that I am not aware of. Please help if you can. Here is my code from the global HTML:
function popoverHandler(event) {
//check for popover opening
if (event.target.identifier === "MyPopUp") {
//send message to injected script to send page info
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("getContent", '', false);
//this works fine, I get this message every time popover opens
console.log('getContent message sent');
//listen for message containing page info from injected script
safari.application.addEventListener('message', function (messageEvent) {
//only get message from current tab
if (messageEvent.name === "pageInfo" && messageEvent.message.url === safari.application.activeBrowserWindow.activeTab.url) {
pageInfo = messageEvent.message;
//the problem seems to be in here. Every time I open the popover, //I get the current page info plus all the page info messages from //the previous time I open the pover, all duplicates of the previous //messges
console.log(pageInfo);
// call a function in the popover, passing the pageInfo data //received from the injected script
safari.extension.popovers[0].contentWindow.onPageDetailsReceived(pageInfo);
}
});
}
}
Ok, so I was able to solve the problem. First of all, I separated the popoverHandler from the eventListener. For some reason, it was firing the function too many times and returning several lists of the same images. The major issue, however, was that in the popover.js, I was storing the list of images as a var. When I removed the var, the data stopped persisting and I was getting a fresh list every time.

jquery mobile trigger 'create' not working except the first time

I am using jQuery Mobile to create a site, in the index page I placed here a form for a search. I hooked submit event for ajax post. When ajax success get the resource
(html,<ul>...</ul>), placed in the target container, then trigger the create event for enhance the view. This work fine in the first time. When I click back to index page and search again I got a raw listview without enhance, who can tell me why? ps: I have tried many methods but there is more and more problem, the official document was so poor.
$(document).bind('pageinit',function(){
$("#search").submit(function(){
var searchdata = $("#search").serialize();
$.ajax({
'type':"POST",
'url':"/server/jnulib.php?action=search",
'data':searchdata,
'success':function(data){
$("#searchresultfield > ul").remove();
$("#searchresultfield").html(data).find('ul').trigger('create');
try{
$("#searchresultfield > ul").listview('refresh');
}catch(e){
}
$.mobile.changePage("#searchresult");
//$("div[data-role='header'] > a").
}
});
return false;
});
});
EDIT: Test Url: http://ijnu.sinaapp.com
Another problem: the second ajax request failed and the browser navigate to the ajax target straightly.
You could try changing:
$("#searchresultfield").html(data).find('ul').trigger('create');
to:
$("#searchresultfield").html(data).find('ul').listview().listview('refresh');
Anytime you append or remove elements you need to refresh, and if you remove the whole list, you need to reinitialize it.
Also I have had issues with listview('refresh') rendering improperly if it was not visible.
$(document).on('pageshow','div',function(event, ui){
if($("#searchresultfield > ul").is(":visible")) $("#searchresultfield > ul").listview('refresh');
});
For me, .trigger('create'); always works if applied to the element with data-role="page"
For example
HTML Code
<div data-role="page" id="somePage">
...
</div>
Javascript Code
$('#somePage').trigger('create');
Hope it helps
Try:
$("#searchresultfield > ul").empty();
instead of
$("#searchresultfield > ul").remove();
I think the problem is that jquery mobile loads all pages despite all being from different files into one big page and navigation is based off going to different points in this page, so that when you go onto it the first time the page you access is considered created however when clicking the back button and navigating away from the page that page is still considered created so the event well not fire again,
What I used was:
$('#oppList').live('pageshow',function(event){
getList();
});
Where #opplist is the id of the data-role="page" for the page I just load, this does not matter whether this happens the first time the page is loaded or after because the event is fired whenever the page is displayed.
See Here foe jquery mobile events
Also see here for jquery mobile navigation
Hope this helps !
Maybe you should try to unhook the submit event once it's been handled. And initiate it again once you go back to the page where you were before. Adding eventhandlers multiple times can cause a lot of problems.

replacing content on pages that use ajax

I'm working on a extension for a fb game that adds some extra info to popup boxes, hides some useless information and run some timers so you can see how long till you have to do something even if you are not on the game page.
My problem is that a while back they went over to using ajax to change between pages and I am wondering if I am using the right approach to handle this.
I run a setInterval that checks if I am on a page where i want to add/remove soemting and i havent done it yet, if this is true I do my stuff, the code looks something like this:
function myFunction() {
if($(selector for some element I am looking for).length > 0 && $(selector for some item I add).length == 0) {
//do some stuff
}
}
setInterval("myFunction()",1000);
Is this the right way of handling ajax page change from an content script in an extension?
If so is there a better way to see if I am on the right page or if i have added to this page already other than doing a selection?
You can use livequery jquery plugin to catch when new element is created on a page:
$("#ajax-element").livequery(function({
//ajax-element is created
});
You can also listen to DOMSubtreeModified event which fires when DOM changes:
document.addEventListener("DOMSubtreeModified", function(event){
//something has changed, possibly ajax-element was added
});
There are also more specific DOMNodeInsertedIntoDocument and DOMNodeRemovedFromDocument events.

Click count possible with javascript?

Let's say, in website, I want to display the notice message block whenever people click any of the link at my website more than x number of times. Is that possible to count with javascript and display the notice message block ? And can we count the refresh times also ? Or can it be only done with server side language like php ? Please kindly suggest. Thank you.
With Regards,
To do something when any link is clicked is best done with JQuery's live:
Description: Attach a handler to the
event for all elements which match the
current selector, now and in the
future.
$('a').live('click', function() {
// Live handler called.
});
Even if you add more links in run time, this will take care of it.
For counting refreshes I would do it with ajax calls on window.load event, or if you want to use new tech - store it locally with Html5. :-)
You can do that on the client. However, this will be limited to the browser. The simplest will be to store this information in cookies on the client. For instance with jQuery you could simply intercept clicks like that:
$("a").click(function() {
var clickedUrl = $(this).attr('href');
// Here you update the cookie for the count of clicks for that A URL
});
I would either count page refreshes serverside or probably call an ajax function to update the count when the page loads.
If you want to count clicks you may need to bind an event to each link and then for each indivisual button store the number of clicks in global variables...
You could register each click event on the document by using:
$(document).click(function()
{
// Check the number in the cookie and add another
// click to the cookie
});
Then you could use the jQuery cookie plugin to store that value and check it each time there is a click (in the function above).
here's the cookie plugin: https://github.com/carhartl/jquery-cookie
I threw together a quick example. If you're not worried about doing this from page to page then you don't need cookies, just store it in a variable:
http://www.webdesignandseo.net/jquery/clickcount/

jQuery code repeating problem

I have a piece of code in jQuery that I use to get the contents of an iFrame after you click a link and once the content is completed loading. It works, but I have a problem with it repeating - at least I think that is what it is doing, but I can't figure out why or how.
jQuery JS:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
$("#fileuploadframe").load(function(){
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{action:"savePage",html:response, id: theID},
function(data){
alert(data);
});
});
});
HTML Links ( one of many ):
<a href="templates/1000/files/index.php?pg=0&preview=false"
target="fileuploadframe" class="pageSaveButton" rel="0">Home</a>
So when you click the link, the page that is linked to is opened into the iframe, then the JS fires and waits for the content to finish loading and then grabs the iframe's content and sends it to a PHP script to save to a file. I have a problem where when you click multiple links in a row to save multiple files, the content of all the previous files are overwritten with the current file you have clicked on. I have checked my PHP and am pretty positive the fault is with the JS.
I have noticed that - since I have the PHP's return value alerted - that I get multiple alert boxes. If it is the first link you have clicked on since the main page loaded - then it is fine, but when you click on a second link you get the alert for each of the previous pages you clicked on in addition to the expected alert for the current page.
I hope I have explained well, please let me know if I need to explain better - I really need help resolving this. :) (and if you think the php script is relevant, I can post it - but it only prints out the $_POST variables to let me know what page info is being sent for debugging purposes.)
Thanks ahead of time,
Key
From jQuery .load() documentation I think you need to change your script to:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
var lnk = $(this).attr("href");//LINK TO LOAD
$("#fileuploadframe").load(lnk,
function(){
//EXECUTE AFTER LOAD IS COMPLETE
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{
action:"savePage",
html:response,
id: theID
},
function(data){alert(data);}
);
});
});
As for the multiple responses, you can use something like blockui to disable any further clicks till the .post call returns.
This is because the line
$("#fileuploadframe").load(function(){
Gets executed every time you press a link. Only add the loadhandler to the iframe on document.ready.
If a user has the ability via your UI to click multiple links that trigger this function, then you are going to run into this problem no matter what since you use the single iframe. I would suggest creating an iframe per save process, that why the rendering of one will not affect the other.

Categories

Resources