How do I get javascript to run when pdfjs is loaded? - javascript

Trying to auto-search with pdfjs, (and having hard time with the docs..)
THIS WORKS:
<input type="button" value="click-me" onclick="searchPDF('cpu');" />
THIS DOESN'T (jquery running ok)
$(document).ready(function() {
searchPDF('cpu');
});
HOW DO SUSPEND EXECUTION UNTIL THE PDF IS PARSED? (OR WHY ISN'T IT WORKING)
MODIFIED viewer.html (thanks to PDF.js - Using search function on embedded PDF )
// search with PDF.js
function searchPDF(td_text) {
//PDFView.findBar.open();
$('#findInput').val(td_text);
$("#tableDiv").focus();
PDFView.findBar.findNextButton.click();
var event = document.createEvent('CustomEvent');
event.initCustomEvent('find', true, true, {
query: td_text,
caseSensitive: $("#findMatchCase").prop('checked'),
highlightAll: $("#findHighlightAll").prop('checked'),
findPrevious: undefined
});
return event;

Finally found a solution for us that doesn't digest javascript for breakfast:
(thanks to
Based on viewer.html and added jquery:
$(document).ready(function() {
document.addEventListener('textlayerrendered', function (e) {
if (e.detail.pageNumber === PDFView.page) {
// finished rendering, call a JS-function..
searchPDF('cpu');
}
}, true);
});
function searchPDF(str) {
alert('working');
..add code from
http://stackoverflow.com/questions/38976490/how-do-i-get-javascript-to-run-when-pdfjs-is-loaded
}

Related

Execute javascript once Record view is fully loaded in SugarCrm 7.2

You can add JS events in SugarCRM 7.2 by creating a custom record.js.
The problem I'm having is that they fire before the page is loaded so elements I'm trying to affect don't exist.
I have tried the following:
$(document).ready(function() { alert(0); }) // fires before page is loaded
$(document).on('load', function() { alert(1); }) // doesn't fire at all
$(window).load(function() { alert(2); }) // doesn't fire at all
Any help in resolving this would be much appreciated.
record.js
({
extendsFrom: 'RecordView',
initialize: function (options) {
this._super('initialize', [options]);
SUGAR.util.ajaxCallInProgress = function () {
alert(0);
$('[name="duplicate_button"]').hide();
},
})
The way I got this to work was to use the following code in custom/modules//clients/base/views/record/record.js
({
extendsFrom: 'AccountsRecordView',
initialize: function (options) {
this._super('initialize', [options]);
this.on("render", this.SetHomeButtons, this); //calls SetHomeButtons
},
SetHomeButtons: function () {
some code ....
},
})
The function SetHomeButtons is called once the page is loaded
Another way of doing it is to overwrite the render function to call your custom code
That doesn't work because of AJAX.
Edit: in Sugar 7 you have the function SUGAR.util.ajaxCallInProgress() it retruns false when every Request is done (all Content Elements have been loaded)

Javascript not working when jquery is added

I am new to javascript n jquery. I used javascript along with jquery on my script tag.When jquery is not added, the javascript works fine,but when a jquery function is added, the script is not working.....shall i convert both to javascript or both to jquery or am i missing anything.Here is my script
<script type="text/javascript">
function getLocations() {
$.post('#Url.Action("getLocations","Home")', { 'id': $("#cities").val() },
function (data) {
$("#loca").html(data).show();
});
}
$(function () {
$('.submit').on('click', function () {
var ck = "";
var city = $("#cities option:selected").text();
var location = $("#loca option:selected").text();
alert(city+"and"+location)
}
});
</script>
here i am loading location based on the city selected.Its works fine when the onclick is not there,But when added ,location are not loading n the function is not calling.I have tried by butting alert inside it.Do i need do any thing else for both to work....Thank You
you forgot a )
$(function () {
$('.submit').on('click', function () {
...
}) // <---
});
if you properly indent the code blocks and if you look on the javascript console, this kind of errors become easier to be detected. Just adopt an indent style and write code adhering to it.

automatic clicks on links and doing something with every page's DOM

i have some links in a web page ,what i want to do :
Trigger click event on every link
When the page of every link is loaded , do something with page's DOM(fillProducts here)
What i have tried :
function start(){
$('.category a').each(function(i){
$.when($(this).trigger('click')).done(function() {
fillProducts() ;
});
})
}
Thanks
What you want to do is much more complicated than you seem to be giving it credit for. If you could scrape webpages, including AJAX content, in 7 lines of js in the console of a web browser you'd put Google out of business.
I'm guessing at what you want a bit, but I think you want to look at using a headless browser, e.g. PhantomJs. You'll then be able to scrape the target pages and write the results to a JSON file (other formats exist) and use that to fillProducts - whatever that does.
Also, are you stealing data from someone else's website? Cause that isn't cool.
Here's a solution that may work for you if they are sending their ajax requests using jQuery. If they aren't you're going to need to get devilishly hacky to accomplish what you're asking (eg overriding the XMLHttpRequest object and creating a global observer queue for ajax requests). As you haven't specified how they're sending the ajax request I hope this approach works for you.
$.ajaxSetup({
complete: function(jQXHR) {
if(interested)
//do your work
}
});
The code below will click a link, wait for the ajax request to be sent and be completed, run you fillProducts function and then click the next link. Adapting it to run all the clicks wouldn't be difficult
function start(){
var links = $('.category a');
var i = 0;
var done = function() {
$.ajaxSetup({
complete: $.noop//remove your handler
});
}
var clickNext = function() {
$(links.get(i++)).click();//click current link then increment i
}
$.ajaxSetup({
complete: function(jQXHR) {
if(i < links.length) {
fillProducts();
clickNext();
} else {
done();
}
}
});
clickNext();
}
If this doesn't work for you try hooking into the other jqXHR events before hacking up the site too much.
Edit here's a more reliable method in case they override the complete setting
(function() {
var $ajax = $.ajax;
var $observer = $({});
//observer pattern from addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjquery
var obs = window.ajaxObserver = {
subscribe: function() {
$observer.on.apply($observer, arguments);
},
unsubscribe: function() {
$observer.off.apply($observer, arguments);
},
once: function() {
$observer.one.apply($observer, arguments);
},
publish: function() {
$observer.trigger.apply($observer, arguments);
}
};
$.ajax = function() {
var $promise = $ajax.apply(null, arguments);
obs.publish("start", $promise);
return $promise;
};
})();
Now you can hook into $.ajax calls via
ajaxObserver.on("start", function($xhr) {//whenever a $.ajax call is started
$xhr.done(function(data) {
//do stuff
})
});
So you can adapt the other snippet like
function start(){
var links = $('.category a');
var i = 0;
var clickNextLink = function() {
ajaxObserver.one("start", function($xhr) {
$xhr.done(function(data) {
if(i < links.length) {
fillProducts();
clickNextLink();
} else {
done();
}
});
})
$(links.get(i++)).click();//click current link then increment i
}
clickNextLink();
}
try this:
function start(){
$('.category a').each(function(i){
$(this).click();
fillProducts() ;
})
}
I get ya now. This is like say:
when facebook loads, I want to remove the adverts by targeting specific class, and then alter the view that i actually see.
https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/
Is a plugin for firefox, this will allow you to create a javascript file, will then allow you to target a specific element or elements within the html rendered content.
IN order to catch the ajax request traffic, you just need to catcher that within your console.
I can not give you a tutorial on greasemonkey, but you can get the greasemonkey script for facebook, and use that as a guide.
http://mashable.com/2008/12/25/facebook-greasemonkey-scripts/
hope this is it

Loading GIF while AJAX completes

This should be quite simple but I'll be darned if I can work it out. Just trying to get a div to display while my ajax is processing and then hide once done (I've put a sleep in there purely to test its working as locally it loads so fast I'm not sure if its working or not)!
The html page has this code in the script: -
$(document).ready(function(){
$("#loadingGIF").ajaxStart(function () {
$(this).show();
});
$("#loadingGIF").ajaxStop(function () {
window.setTimeout(partB,5000)
$(this).hide();
});
function partB(){
//just because
}
var scenarioID = ${testScenarioInstance.id}
var myData = ${results as JSON}
populateFormData(myData, scenarioID);
});
There is then a div in my page like so (which I can see in the source of the page just hidden): -
<div id="loadingGIF" ><img src='${application.contextPath}/images/spinner.gif' height="50" width="50"></div>
The ready code then goes off and calls this: -
function populateFormData(results, scenarioID) {
$table = $('#formList')
for(var i in results){
var formIDX = (results[i]["forms_idx"])
var formID = (results[i]["form_id"])
appendSubTable(formIDX, scenarioID, $table, formID);
}
}
Which references this multiple times calling several AJAX posts: -
function appendSubTable(formIDX, scenarioID, $table, formID) {
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url = "**Trust me this bits OK ;) **"
$.post(url, {
formIDX : formIDX, scenarioID : scenarioID, formID :formID
}, function(data) {
$subTable.append(data)
}).fail(function() {
});
}
Any pointers gratefully received...
Interestingly I bunged some alerts into my ajaxstart and stop and neither show up ever so I'm missing something obvious :S When I check the console in firefox I can see that all my POSTs are completing....
You should probably add the Ajaxstart and stop global event handlers to the document node like this
$(document).ajaxStart(function () {
$("#loadingGIF").show();
});
I realized my problem, I needed to register the ajaxstart and stop to the document not the div!
So instead of this: -
$("#loadingGIF").ajaxStart(function () {
$(this).show();
});
I now have: -
$(document).ajaxStart(function () {
$("#loadingGIF").show();
});
I assume this is because its the document that the ajax is running against not the div although my understanding there may not be 100% accurate at least this works so please tell me if I've misunderstood this! :)
#jbl, thanks for this pointer I did this to also leave the notification on screen for a few more moments just to make sure everything is loaded.

Dynamically adding script to a div does not execute the script

PROBLEM:
Why does this not show the alert? And how can I make it so?
<script>
function onSuccess() {
var response= "<script> alert(1);</\script>";
document.getElementById("xxx").innerHTML = response;
}
</script>
<div id="xxx">existing text</div>
<button id="click" onclick="onSuccess();">click</button>
http://jsfiddle.net/7hWRR/1/
This is just a simplified version of my problem. In our application (in one very old module in particular) we use an ancient home-grown AJAX class which just innerHTMLs all AJAX responses.Traditionally we have only sent back HTML as AJAX response but I would like to execute JS in the success handler.I do not have access to the JS file so cannot modify the way the response is handled. I can only work with the fact that the success handler calls div.innerHTML='<my response>'
So stupid as it may be, I'm hoping for some help using these constraints!
SIMILAR LINKS:
Dynamically adding script element to a div does not execute the script
Dynamically added script will not execute
Caveat: Here I'm assuming the <div> on which the results are inserted is known.
A possible solution is to use a MutationObserver (and the DOMNodeInserted event, to support IE 9 and 10) to watch said <div> for changes on its contents, and execute the code on any inserted <script> tags.
Example built upon your jsFiddle:
watchNodeForScripts(document.getElementById("xxx"));
function watchNodeForScripts(scriptRecipient) {
if ('MutationObserver' in window) {
// Prefer MutationObserver: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
watchUsingMutationObserver();
} else {
// Fallback to Mutation Events: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Events/Mutation_events
watchUsingDeprecatedMutationEvents();
}
function watchUsingMutationObserver() {
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
var i, addedNodes = mutation.addedNodes;
for (i = 0; i < addedNodes.length; i++) {
handleAddedNode(addedNodes[i]);
}
});
});
observer.observe(scriptRecipient, {
childList: true
});
}
function watchUsingDeprecatedMutationEvents() {
scriptRecipient.addEventListener("DOMNodeInserted", function (event) {
handleAddedNode(event.target);
});
}
function handleAddedNode(node) {
// Don't try to execute non-script elements
if (!(node instanceof HTMLScriptElement)) return;
// Don't try to execute linked scripts
if (node.src !== "") return;
// Use 'new Function' instead of eval to avoid
// the creation of a (undesired) closure
fn = new Function(node.textContent);
fn.call(window);
}
}
Updated fiddle: http://jsfiddle.net/7hWRR/13/
Edit: Changed innerText to the more cross-compatible textContent.
Edit2: Don't execute code that isn't inside a <script> element.
Edit3: Don't execute scripts with the src attribute, and add mutation events fallback

Categories

Resources