I am trying to render a pdf in chrome using PDFJS
This is the function I am calling:
open: function pdfViewOpen(url, scale, password) {
var parameters = {password: password};
if (typeof url === 'string') { // URL
this.setTitleUsingUrl(url);
parameters.url = url;
} else if (url && 'byteLength' in url) { // ArrayBuffer
parameters.data = url;
}
if (!PDFView.loadingBar) {
PDFView.loadingBar = new ProgressBar('#loadingBar', {});
}
this.pdfDocument = null;
var self = this;
self.loading = true;
getDocument(parameters).then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
self.loading = false;
},
function getDocumentError(message, exception) {
if (exception && exception.name === 'PasswordException') {
if (exception.code === 'needpassword') {
var promptString = mozL10n.get('request_password', null,
'PDF is protected by a password:');
password = prompt(promptString);
if (password && password.length > 0) {
return PDFView.open(url, scale, password);
}
}
}
var loadingErrorMessage = mozL10n.get('loading_error', null,
'An error occurred while loading the PDF.');
if (exception && exception.name === 'InvalidPDFException') {
// change error message also for other builds
var loadingErrorMessage = mozL10n.get('invalid_file_error', null,
'Invalid or corrupted PDF file.');
//#if B2G
// window.alert(loadingErrorMessage);
// return window.close();
//#endif
}
var loadingIndicator = document.getElementById('loading');
loadingIndicator.textContent = mozL10n.get('loading_error_indicator',
null, 'Error');
var moreInfo = {
message: message
};
self.error(loadingErrorMessage, moreInfo);
self.loading = false;
},
function getDocumentProgress(progressData) {
self.progress(progressData.loaded / progressData.total);
}
);
}
This is the call:
PDFView.open('/MyPDFs/Pdf2.pdf', 'auto', null);
All I get is this:
If you notice, even the page number is retrieved but the content is not painted in the pages. Can´t find why.. Is the any other function I should call next to PDFView.open?
Found the solution...!
This is the code that does the work.
$(document).ready(function () {
PDFView.initialize();
var params = PDFView.parseQueryString(document.location.search.substring(1));
//#if !(FIREFOX || MOZCENTRAL)
var file = params.file || DEFAULT_URL;
//#else
//var file = window.location.toString()
//#endif
//#if !(FIREFOX || MOZCENTRAL)
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
document.getElementById('openFile').setAttribute('hidden', 'true');
} else {
document.getElementById('fileInput').value = null;
}
//#else
//document.getElementById('openFile').setAttribute('hidden', 'true');
//#endif
// Special debugging flags in the hash section of the URL.
var hash = document.location.hash.substring(1);
var hashParams = PDFView.parseQueryString(hash);
if ('disableWorker' in hashParams)
PDFJS.disableWorker = (hashParams['disableWorker'] === 'true');
//#if !(FIREFOX || MOZCENTRAL)
var locale = navigator.language;
if ('locale' in hashParams)
locale = hashParams['locale'];
mozL10n.setLanguage(locale);
//#endif
if ('textLayer' in hashParams) {
switch (hashParams['textLayer']) {
case 'off':
PDFJS.disableTextLayer = true;
break;
case 'visible':
case 'shadow':
case 'hover':
var viewer = document.getElementById('viewer');
viewer.classList.add('textLayer-' + hashParams['textLayer']);
break;
}
}
//#if !(FIREFOX || MOZCENTRAL)
if ('pdfBug' in hashParams) {
//#else
//if ('pdfBug' in hashParams && FirefoxCom.requestSync('pdfBugEnabled')) {
//#endif
PDFJS.pdfBug = true;
var pdfBug = hashParams['pdfBug'];
var enabled = pdfBug.split(',');
PDFBug.enable(enabled);
PDFBug.init();
}
if (!PDFView.supportsPrinting) {
document.getElementById('print').classList.add('hidden');
}
if (!PDFView.supportsFullscreen) {
document.getElementById('fullscreen').classList.add('hidden');
}
if (PDFView.supportsIntegratedFind) {
document.querySelector('#viewFind').classList.add('hidden');
}
// Listen for warnings to trigger the fallback UI. Errors should be caught
// and call PDFView.error() so we don't need to listen for those.
PDFJS.LogManager.addLogger({
warn: function () {
PDFView.fallback();
}
});
var mainContainer = document.getElementById('mainContainer');
var outerContainer = document.getElementById('outerContainer');
mainContainer.addEventListener('transitionend', function (e) {
if (e.target == mainContainer) {
var event = document.createEvent('UIEvents');
event.initUIEvent('resize', false, false, window, 0);
window.dispatchEvent(event);
outerContainer.classList.remove('sidebarMoving');
}
}, true);
document.getElementById('sidebarToggle').addEventListener('click',
function () {
this.classList.toggle('toggled');
outerContainer.classList.add('sidebarMoving');
outerContainer.classList.toggle('sidebarOpen');
PDFView.sidebarOpen = outerContainer.classList.contains('sidebarOpen');
PDFView.renderHighestPriority();
});
document.getElementById('viewThumbnail').addEventListener('click',
function () {
PDFView.switchSidebarView('thumbs');
});
document.getElementById('viewOutline').addEventListener('click',
function () {
PDFView.switchSidebarView('outline');
});
document.getElementById('previous').addEventListener('click',
function () {
PDFView.page--;
});
document.getElementById('next').addEventListener('click',
function () {
PDFView.page++;
});
document.querySelector('.zoomIn').addEventListener('click',
function () {
PDFView.zoomIn();
});
document.querySelector('.zoomOut').addEventListener('click',
function () {
PDFView.zoomOut();
});
document.getElementById('fullscreen').addEventListener('click',
function () {
PDFView.fullscreen();
});
document.getElementById('openFile').addEventListener('click',
function () {
document.getElementById('fileInput').click();
});
document.getElementById('print').addEventListener('click',
function () {
window.print();
});
document.getElementById('download').addEventListener('click',
function () {
PDFView.download();
});
document.getElementById('pageNumber').addEventListener('change',
function () {
PDFView.page = this.value;
});
document.getElementById('scaleSelect').addEventListener('change',
function () {
PDFView.parseScale(this.value);
});
document.getElementById('first_page').addEventListener('click',
function () {
PDFView.page = 1;
});
document.getElementById('last_page').addEventListener('click',
function () {
PDFView.page = PDFView.pdfDocument.numPages;
});
document.getElementById('page_rotate_ccw').addEventListener('click',
function () {
PDFView.rotatePages(-90);
});
document.getElementById('page_rotate_cw').addEventListener('click',
function () {
PDFView.rotatePages(90);
});
//#if (FIREFOX || MOZCENTRAL)
//if (FirefoxCom.requestSync('getLoadingType') == 'passive') {
// PDFView.setTitleUsingUrl(file);
// PDFView.initPassiveLoading();
// return;
//}
//#endif
//#if !B2G
PDFView.open(file, 0);
//#endif
});
The system must be initialized first before PDFView.open call!
Thanks
Related
I am trying to get my chat script to work I have moved to a VPS thinking that should solve any missing extensions but I have the same problem.
A user logs into the website and can then load the chat to talk with other members - I am using the datingframework
in the console window I can see the message but socket.io keeps timing out I have tried using different ports and changing from https - http but get the same error
On their demo website when I send a chat I notice a different scroll event getting triggered before the message is displayed.
This is some of the chat js code as there is a limit on the amount I can post!!
/* this is main chat controller */
App.controller('WebsocketChatController',function($scope,$rootScope,$http, socket, $timeout,$location,$anchorScroll,Upload,$log,$timeout,screenSize) {
$scope.getSocketObj= function()
{
return socket;
}
/* socket operations */
$scope.socket_id = 0;
socket.on('connected', function(data){
$scope.socket_id = data.socket_id;
$scope.mapUserWithSocket();
});
//if not in chatUsers array take from ajax call
socket.on("new_message_received", function(data){
//$scope.getChatUsers();
var text = parseInt($(".notification-message").html());
if(isNaN(text)){
text= 0;
}
$(".notification-message").html(text+1);
console.log(JSON.stringify(data));
toastr.success(recieved_msg);
var user = $scope.findUserByID(data.from_user);
//toastr.success('You got a new message from '+user.user.name);
if(data.to_user==$scope.authUser)
{
data.recipient='other';
}
else
{
data.recipient='self';
}
user.user.messages.push(data);
if (user.user.last_msg == "" && user.user.id == $scope.chatUsers[$scope.selected].user.id) {
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
$("#fourth_div").hide();
}
if (data.type == 2) {
user.user.last_msg = data.meta;
user.user.last_msg_type = 2;
} else if (data.type == 0) {
user.user.last_msg = data.text;
user.user.last_msg_type = 0;
}
user.user.total_messages_count += 1;
var curr_user_id= "user-"+user.user.id;
//if user selected and user msg recieved are differed=nt then increment otherwise no
if(curr_user_id != $(".all_users").parent().find('.active').data('id'))
{
user.user.total_unread_messages_count += 1;
$scope.overall_unread_messages_count += 1;
}
var audio = new Audio("#plugin_asset('WebsocketChatPlugin/audio/ping.mp3')");
audio.play();
//$("#chat-container").scrollTop($("#chat-container").find("> .img_main_div_padding").height());
});
socket.on("new_message_sent", function(data){
var user = $scope.findUserByID(data.to_user);
if(data.to_user==$scope.authUser)
{
data.recipient='other';
}
else
{
data.recipient='self';
}
user.user.messages.push(data);
if (user.user.last_msg == "" && user.user.id == $scope.chatUsers[$scope.selected].user.id) {
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
$("#fourth_div").hide();
}
if (data.type == 2) {
user.user.last_msg = data.meta;
user.user.last_msg_type = 2;
} else if (data.type == 0) {
user.user.last_msg = data.text;
user.user.last_msg_type = 0;
}
// user.user.total_messages_count += 1;
// user.user.total_unread_messages_count += 1;
//$("#chat-container").scrollTop($("#chat-container").find("> .img_main_div_padding").height());
});
/*end of socket operations */
/* user online offline status */
socket.on('user_online', function(data){
var user = $scope.findUserByID(data.user_id);
if (user) {
user.online = 1;
}
});
socket.on('user_offline', function(data){
var user = $scope.findUserByID(data.user_id);
if (user) {
user.online = 0;
}
});
/* end user online offline status */
//event listening to contact delete
socket.on('contact_deleted', function(data){
$scope.getChatUsers();
});
$scope.isTypingUser=0;
/* typing stop and start notification */
socket.on('typing', function(data){
var user = $scope.findUserByID(data.from_user);
if (user) {
user.user.isTyping = true;
console.log(user.user.name + " is typing..");
//$scope.isTypingUser=1;
$('#typing_'+user.user.id).show();
}
});
socket.on('typing_stop', function(data){
var user = $scope.findUserByID(data.from_user);
if (user) {
user.user.isTyping = false;
console.log(user.user.name + " is stopped typing..");
$('#typing_'+user.user.id).hide();
}
});
$scope.typing = function(){
if (!$scope.type) {
$scope.type = true;
socket.emit('typing', {from_user: auth_user_id_chat, to_user:$scope.chatUsers[$scope.selected].user.id });
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= 2000 && $scope.type) {
socket.emit('typing_stop', {from_user: auth_user_id_chat, to_user:$scope.chatUsers[$scope.selected].user.id });
$scope.type = false;
}
}, 2000);
}
/* end typing stop and start notification */
/* new user contacted */
socket.on("new_user_contacted", function(data){
var user = $scope.findUserByID(data.user_id);
/* if user is already in list then remove*/
if (user) {
if(!$scope.total_contacts_count)
{
$scope.chatUsers=[];
}
else
{
var index = $scope.chatUsers.indexOf(user);
$scope.chatUsers.splice(index, 1);
}
}
//push object again retriving ajax call
$http.post(chat_user, {user_id:data.user_id})
.then(function(response){
if (response.data.status == 'success') {
//$scope.chatUsers.push(response.data.chat_user);
var temp = [];
temp.push(response.data.chat_user);
$scope.chatUsers = $.merge(temp, $scope.chatUsers);
$scope.chatUsers = _.uniq($scope.chatUsers, function(a) { return a.contact_id; });
}
}
,function(response){});
});
/* end new user contacted */
$scope.findUserByID = function(user_id){
if ($scope.chatUsers.length < 1)
return null;
return $scope.chatUsers.find(function(item){
if(item.user.id == user_id) return true;
});
}
$scope.mapUserWithSocket = function() {
$http.post(map_user_socket,
{socket_id:$scope.socket_id}).then(function(response){
if (response.data.status == 'success') {
socket.emit('user_socket_mapped', {user_id:auth_user_id_chat})
console.log('you are connected');
}
}, function(){});
}
function swapElement(array, indexA, indexB) {
var tmp = array[indexA];
array[indexA] = array[indexB];
array[indexB] = tmp;
return array;
}
$scope.chatUsers = [];
$scope.chat_users_count = 0;
$scope.total_contacts_count = 0;
$scope.last_contact_id = 0;
$scope.authUser = auth_user_id_chat;
$scope.overall_unread_messages_count = 0;
/* this method gets chat users */
$scope.getChatUsers = function(){
$http.get(
chat_users,
{last_contact_id:$scope.last_contact_id}
).then(function(res){
if(res.data.status == "success") {
$scope.total_contacts_count = res.data.total_contacts_count;
$scope.chatUsers = res.data.chat_users;
if($scope.contact_id_already_contacted)
{
_.each($scope.chatUsers, function(listItem,index){
if(listItem.contact_id == $scope.contact_id_already_contacted)
$scope.indexToBeSelected = index;
})
$scope.chatUsers = swapElement($scope.chatUsers, $scope.indexToBeSelected,0);
}
$scope.chat_users_count = $scope.chatUsers.length;
if ($scope.total_contacts_count == 0 || $scope.chat_users_count == 0) {
$scope.last_contact_id = 0;
} else {
$scope.last_contact_id = $scope.chatUsers[$scope.chat_users_count-1].contact_id;
}
if ($scope.total_contacts_count != 0 && $scope.load_chat_data_first == true) {
$scope.loadChatDataFirst();
$('#fourth_div').hide();
}
else
{
$('#fourth_div').show();
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").hide();
}
$scope.overall_unread_messages_count = res.data.overall_unread_messages_count;
}
}, function(res){});
}
/* this method retrives message of a particular user */
$scope.getMessages = function(user){
$http.post(
msgs_chat,
{user_id:user.user.id, last_message_id:$scope.last_message_id}
).then(function(res){
if (res.data.status == 'success') {
var temp = [];
$.merge(temp, res.data.messages);
_.each(temp,function(item,index){
if(item.to_user==$scope.authUser)
{
temp[index].recipient='other';
}
else
{
temp[index].recipient='self';
}
})
user.user.messages = $.merge(temp, user.user.messages);
}
}, function(res){});
}
/* this method is used to send message */
$scope.submitMessage = function(){
console.log('$scope.messageInput',$scope.messageInput);
var to_send_user = $scope.chatUsers[$scope.selected];
if($scope.messageInput.indexOf(':')==0)
$scope.messageInput = emojione.shortnameToUnicode($scope.messageInput)
var msg_obj = {
from_user : auth_user_id_chat,
to_user : to_send_user.user.id,
contact_id : to_send_user.contact_id,
message_type : 0,
message_text : $scope.messageInput
};
if(to_send_user.user.can_init_chat)
{
socket.emit('new_message', msg_obj);
}
else{
if(to_send_user.user.init_chat_error_type === 'CHAT_INIT_HOURS_EXPIRED')
{
$('#myModalExceedsChatHourExpired').modal('show');
}
else if(to_send_user.user.init_chat_error_type === 'CHAT_LIMIT_OF_DAY')
{
$('#myModalExceedsChatLimit').modal('show');
}
Plugin.fire('chat_init_send_gift', [to_send_user]);
}
$scope.messageInput='';
}
/* submit messege with media
/* this method is used to send message */
$scope.submitMessageWithMedia = function(image_name){
var to_send_user = $scope.chatUsers[$scope.selected];
var msg_obj = {
from_user : auth_user_id_chat,
to_user : to_send_user.user.id,
contact_id : to_send_user.contact_id,
message_type : 2,
message_text : image_name
};
if(to_send_user.user.can_init_chat)
{
socket.emit('new_message', msg_obj);
}
else{
if(to_send_user.user.init_chat_error_type === 'CHAT_INIT_HOURS_EXPIRED')
{
$('#myModalExceedsChatHourExpired').modal('show');
}
else if(to_send_user.user.init_chat_error_type === 'CHAT_LIMIT_OF_DAY')
{
$('#myModalExceedsChatLimit').modal('show');
}
Plugin.fire('chat_init_send_gift', [to_send_user]);
}
}
$scope.submitMessageFirstTime = function(){
var to_send_user = $scope.chatUsers[$scope.selected];
if($scope.messageInput.indexOf(':')==0)
$scope.messageInput = emojione.shortnameToUnicode($scope.messageInput)
var msg_obj = {
from_user : auth_user_id_chat,
to_user : to_send_user.user.id,
contact_id : to_send_user.contact_id,
message_type : 0,
message_text : $scope.messageInput
};
if(to_send_user.user.can_init_chat)
{
socket.emit('new_message', msg_obj);
$scope.loadChatData(to_send_user, $scope.selected);
}
else{
if(to_send_user.user.init_chat_error_type === 'CHAT_INIT_HOURS_EXPIRED')
{
$('#myModalExceedsChatHourExpired').modal('show');
}
else if(to_send_user.user.init_chat_error_type === 'CHAT_LIMIT_OF_DAY')
{
$('#myModalExceedsChatLimit').modal('show');
}
Plugin.fire('chat_init_send_gift', [to_send_user]);
}
$scope.messageInput='';
}
$scope.loadOnline =function() {
var counter=0;
$scope.onlineSelectedUsers = _.filter($scope.chatUsers, function (item,index) {
if(item.online && counter==0){
$scope.chatUsers[index].user.already_clicked= 0;
$scope.loadChatData($scope.chatUsers[index],index);
counter++;
}
return item.online;
});
var onlineUsers_count = $scope.onlineSelectedUsers.length;
if(onlineUsers_count == 0)
{
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
}
}
$scope.loadOnline_mobile =function() {
$scope.onlineSelectedUsers = _.filter($scope.chatUsers, function (item) { return item.online; });
if($scope.total_contacts_count)
{
if ($scope.onlineSelectedUsers.length == 0) {
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
return false;
}
$scope.loadChatData($scope.onlineSelectedUsers[0],0);
}
}
$scope.loadMatched = function() {
var counter=0;
$scope.matchedUsers = _.filter($scope.chatUsers, function (item,index) {
if(item.matched && counter==0){
$scope.chatUsers[index].user.already_clicked= 0;
$scope.loadChatData($scope.chatUsers[index],index);
counter++;
}
return item.matched;
});
var matchedUsers_count = $scope.matchedUsers.length;
if(matchedUsers_count == 0)
{
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
}
}
$scope.loadAll =function() {
if($scope.total_contacts_count)
{
if ($scope.chatUsers.length == 0) {
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
return false;
}
$scope.loadChatData($scope.chatUsers[0],0);
}
}
$scope.loadAll_mobile =function() {
if ($scope.chatUsers.length == 0) {
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
return false;
}
if($scope.total_contacts_count)
$scope.loadChatData($scope.chatUsers[0],0);
}
$scope.selected = 0;
$scope.loadChatData = function(user,index) {
//$scope.selected = index;
//index = $scope.chatUsers.indexOf(user);
if(user !=undefined)
{
$scope.current_to_user_id=user.user.id;
if(!$scope.total_contacts_count)
{
$http.post(add_to_contacts, {user_id:user.user.id})
.then(function(response){
if (response.data.status == 'success') {
$scope.getChatUsers();
}
}
,function(response){});
}
//hide the button
$('#load_more').show();
$scope.userChatDetail = user;
$scope.selected = index;
if (user.user.last_msg) {
$scope.last_message_id = 0;
if (user.user.messages.length > 0) {
$scope.last_message_id = user.user.messages[0].id;
}
if(!user.already_clicked) {
$('.loaderChatData').fadeIn();
$scope.getMessages(user);
user.already_clicked = 1;
//clear unread mesg count
user.user.total_unread_messages_count= 0;
//call function to make unread status for this user once i click on unread mesges
//pending
$http.post(
mark_read ,
{user_id:user.user.id}
).then(function(res){
console.log(res);
$('.loaderChatData').fadeOut();
});
}
if(user.already_clicked)
{
//clear unread mesg count
user.user.total_unread_messages_count= 0;
//$scope.getMessages(user);
}
// $scope.last_msg = user.user.last_msg;
// $scope.last_msg_type = user.user.last_msg_type;
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
$("#fourth_div").hide();
if($scope.mobile)
{
$('.mobile_users').hide();
}
}
else
{
$('#third_img_div').hide();
$('#first_img_div').show();
$("#no-users-div").hide();
$("#fourth_div").hide();
if($scope.mobile)
{
$('.mobile_users').hide();
}
}
}
}
$scope.loadMoreChatData =function(user,index,last_msg_id)
{
$scope.userChatDetail = user;
$scope.selected = index;
if (user.user.last_msg) {
$scope.last_message_id = 0;
if (user.user.messages.length > 0) {
$scope.last_message_id = last_msg_id;
}
$scope.getMessages(user);
// $scope.last_msg = user.user.last_msg;
// $scope.last_msg_type = user.user.last_msg_type;
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
}
else
{
$('#third_img_div').hide();
$('#first_img_div').show();
$("#no-users-div").hide();
}
}
$scope.loadChatDataFirst = function() {
$scope.loadChatData($scope.chatUsers[0], 0);
}
});
/* this is socket factory */
App.factory('socket', function ($rootScope) {
var socket = io(websocket_domain+":"+server_port);
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
/* end of socket factory */
i have call the below function in my application
function workerCall() {
debugger;
if (typeof (Worker) !== "undefined") {
var worker = new Worker("Scripts/worker.js");
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
worker.postMessage({ 'username': Username });
function workerResultReceiver(e) {
$('.NotificationCount').html(e.data);
if (parseInt(e.data) != 0 && currentPage == "Alert") {
StateFlag = false;
$('.Notification').show();
$('.Drildown').each(function () {
var temp = this.id;
if ($('#' + temp).attr('expand') == "true") {
currentTab = temp;
StateFlag = true;
}
});
currentScrollPosition = $('body').scrollTop();
GetAlerts();
} else {
$('.Notification').hide();
}
}
function workerErrorReceiver(e) {
console.log("there was a problem with the WebWorker within " + e);
}
}
else {
}
}
the method will execute in IE,Chrome but when comes to Mozilla i got an error ReferenceError: workerResultReceiver is not defined.How can i resolve this error?
This happens because you are making reference to function that is not created yet. You need to put this:
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
Above
function workerErrorReceiver
line or at the end of the scope.
I'm using a jquery plugin called quicksearch within Sharepoint 2010 and it works perfectly. Unfortunately were being forced to migrate onto sharepoint 2013 and it's stopped working. An error is shown saying that the function is undefined. I believe I've narrowed this down to the quicksearch function itself.
Here is the preliminary code:
_spBodyOnLoadFunctionNames.push("Load");
$('[name=search]').on('keyup', function(){
Load();
});
function Load() {
var searchArea = "#cbqwpctl00_ctl22_g_ca6bb172_1ab4_430d_ae38_a32cfa03b56b ul li";
var qs = $('input#id_search_list').val();
qs.quicksearch(searchArea);
$('.filter input').on('change', function(){
checkAndHide()
//$(searchArea).unhighlight();
});
function checkAndHide(){
var inputs = $('.filter input');
var i =0;
for (var i = 0; i < inputs.length; i++){
if (!inputs[i].checked){
$('.' + inputs[i].name).addClass('filter-hide');
} else {
$('.' + inputs[i].name).removeClass('filter-hide');
};
};
};
}
Here is an example of the quicksearch library I'm using:
(function($, window, document, undefined) {
$.fn.quicksearch = function (target, opt) {
var timeout, cache, rowcache, jq_results, val = '', e = this, options = $.extend({
delay: 300,
selector: null,
stripeRows: null,
loader: null,
noResults: 'div#noresults',
bind: 'keyup keydown',
onBefore: function () {
var ar = $('input#id_search_list').val()
if (ar.length > 2) {
var i=0;
var ar2 = $('input#id_search_list').val().split(" ");
for (i = 0; i < ar2.length; i++) {
$(searchArea + ':visible');
}
return true;
}
return false;
checkAndHide()
},
onAfter: function () {
return;
},
show: function () {
this.style.display = "block";
},
hide: function () {
this.style.display = "none";
},
prepareQuery: function (val) {
return val.toLowerCase().split(' ');
},
testQuery: function (query, txt, _row) {
for (var i = 0; i < query.length; i += 1) {
if (txt.indexOf(query[i]) === -1) {
return false;
}
}
return true;
}
}, opt);
this.go = function () {
var i = 0,
noresults = true,
query = options.prepareQuery(val),
val_empty = (val.replace(' ', '').length === 0);
for (var i = 0, len = rowcache.length; i < len; i++) {
if (val_empty) {
options.hide.apply(rowcache[i]);
noresults = false;
} else if (options.testQuery(query, cache[i], rowcache[i])){
options.show.apply(rowcache[i]);
noresults = false;
} else {
options.hide.apply(rowcache[i]);
}
}
if (noresults) {
this.results(false);
} else {
this.results(true);
this.stripe();
}
this.loader(false);
options.onAfter();
return this;
};
this.stripe = function () {
if (typeof options.stripeRows === "object" && options.stripeRows !== null)
{
var joined = options.stripeRows.join(' ');
var stripeRows_length = options.stripeRows.length;
jq_results.not(':hidden').each(function (i) {
$(this).removeClass(joined).addClass(options.stripeRows[i % stripeRows_length]);
});
}
return this;
};
this.strip_html = function (input) {
var output = input.replace(new RegExp('<[^<]+\>', 'g'), "");
output = $.trim(output.toLowerCase());
return output;
};
this.results = function (bool) {
if (typeof options.noResults === "string" && options.noResults !== "") {
if (bool) {
$(options.noResults).hide();
} else {
$(options.noResults).show();
}
}
return this;
};
this.loader = function (bool) {
if (typeof options.loader === "string" && options.loader !== "") {
(bool) ? $(options.loader).show() : $(options.loader).hide();
}
return this;
};
this.cache = function () {
jq_results = $(target);
if (typeof options.noResults === "string" && options.noResults !== "") {
jq_results = jq_results.not(options.noResults);
}
var t = (typeof options.selector === "string") ? jq_results.find(options.selector) : $(target).not(options.noResults);
cache = t.map(function () {
return e.strip_html(this.innerHTML);
});
rowcache = jq_results.map(function () {
return this;
});
return this.go();
};
this.trigger = function () {
this.loader(true);
if (options.onBefore()) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
e.go();
}, options.delay);
}
return this;
};
this.cache();
this.results(true);
this.stripe();
this.loader(false);
return this.each(function () {
$(this).bind(options.bind, function () {
val = $(this).val();
e.trigger();
});
});
};
}(jQuery, this, document));
`
This is where the error comes up:
var qs = $('input#id_search_list').val();
qs.quicksearch(searchArea);
Any help would be appreciated
Turns out was a small issue in the code and major css as sharepoint plays differently in 2013
I am using the excellent onlinejs (https://github.com/PixelsCommander/OnlineJS) library for checking that my app has a live internet connection. However, I don't need it to fire regularly, but rather upon the manual calling of the main function.
I would like to modify this code so that it is not firing on a timer, and know the name of the function to call for manual firing, which assume is just getterSetter.
My previous attempts to modify the code below have broken the script as I'm no expert at JavaScript. I appreciate any help in adapting this very useful code.
function getterSetter(variableParent, variableName, getterFunction, setterFunction) {
if (Object.defineProperty) {
Object.defineProperty(variableParent, variableName, {
get: getterFunction,
set: setterFunction
});
}
else if (document.__defineGetter__) {
variableParent.__defineGetter__(variableName, getterFunction);
variableParent.__defineSetter__(variableName, setterFunction);
}
}
(function (w) {
w.onlinejs = w.onlinejs || {};
//Checks interval can be changed in runtime
w.onLineCheckTimeout = 5000;
//Use window.onLineURL incapsulated variable
w.onlinejs._onLineURL = "http://lascelles.us/wavestream/online.php";
w.onlinejs.setOnLineURL = function (newURL) {
w.onlinejs._onLineURL = newURL;
w.onlinejs.getStatusFromNavigatorOnLine();
}
w.onlinejs.getOnLineURL = function () {
return w.onlinejs._onLineURL;
}
getterSetter(w, 'onLineURL', w.onlinejs.getOnLineURL, w.onlinejs.setOnLineURL);
//Verification logic
w.onlinejs.setStatus = function (newStatus) {
w.onlinejs.fireHandlerDependOnStatus(newStatus);
w.onLine = newStatus;
}
w.onlinejs.fireHandlerDependOnStatus = function (newStatus) {
if (newStatus === true && w.onLineHandler !== undefined && (w.onLine !== true || w.onlinejs.handlerFired === false)) {
w.onLineHandler();
}
if (newStatus === false && w.offLineHandler !== undefined && (w.onLine !== false || w.onlinejs.handlerFired === false)) {
w.offLineHandler();
}
w.onlinejs.handlerFired = true;
};
w.onlinejs.startCheck = function () {
setInterval("window.onlinejs.logic.checkConnectionWithRequest(true)", w.onLineCheckTimeout);
}
w.onlinejs.stopCheck = function () {
clearInterval("window.onlinejs.logic.checkConnectionWithRequest(true)", w.onLineCheckTimeout);
}
w.checkOnLine = function () {
w.onlinejs.logic.checkConnectionWithRequest(false);
}
w.onlinejs.getOnLineCheckURL = function () {
return w.onlinejs._onLineURL + '?' + Date.now();
}
w.onlinejs.getStatusFromNavigatorOnLine = function () {
if (w.navigator.onLine !== undefined) {
w.onlinejs.setStatus(w.navigator.onLine);
} else {
w.onlinejs.setStatus(true);
}
}
//Network transport layer
var xmlhttp = new XMLHttpRequest();
w.onlinejs.isXMLHttp = function () {
return "withCredentials" in xmlhttp;
}
w.onlinejs.isXDomain = function () {
return typeof XDomainRequest != "undefined";
}
//For IE we use XDomainRequest and sometimes it uses a bit different logic, so adding decorator for this
w.onlinejs.XDomainLogic = {
init: function () {
xmlhttp = new XDomainRequest();
xmlhttp.onerror = function () {
xmlhttp.status = 404;
w.onlinejs.processXmlhttpStatus();
}
xmlhttp.ontimeout = function () {
xmlhttp.status = 404;
w.onlinejs.processXmlhttpStatus();
}
},
onInternetAsyncStatus: function () {
try {
xmlhttp.status = 200;
w.onlinejs.processXmlhttpStatus();
} catch (err) {
w.onlinejs.setStatus(false);
}
},
checkConnectionWithRequest: function (async) {
xmlhttp.onload = w.onlinejs.logic.onInternetAsyncStatus;
var url = w.onlinejs.getOnLineCheckURL();
xmlhttp.open("GET", url);
w.onlinejs.tryToSend(xmlhttp);
}
}
//Another case for decoration is XMLHttpRequest
w.onlinejs.XMLHttpLogic = {
init: function () {
},
onInternetAsyncStatus: function () {
if (xmlhttp.readyState === 4) {
try {
w.onlinejs.processXmlhttpStatus();
} catch (err) {
w.onlinejs.setStatus(false);
}
}
},
checkConnectionWithRequest: function (async) {
if (async) {
xmlhttp.onreadystatechange = w.onlinejs.logic.onInternetAsyncStatus;
} else {
xmlhttp.onreadystatechange = undefined;
}
var url = w.onlinejs.getOnLineCheckURL();
xmlhttp.open("HEAD", url, async);
w.onlinejs.tryToSend(xmlhttp);
if (async === false) {
w.onlinejs.processXmlhttpStatus();
return w.onLine;
}
}
}
if (w.onlinejs.isXDomain()) {
w.onlinejs.logic = w.onlinejs.XDomainLogic;
} else {
w.onlinejs.logic = w.onlinejs.XMLHttpLogic;
}
w.onlinejs.processXmlhttpStatus = function () {
var tempOnLine = w.onlinejs.verifyStatus(xmlhttp.status);
w.onlinejs.setStatus(tempOnLine);
}
w.onlinejs.verifyStatus = function (status) {
return status === 200;
}
w.onlinejs.tryToSend = function (xmlhttprequest) {
try {
xmlhttprequest.send();
} catch(e) {
w.onlinejs.setStatus(false);
}
}
//Events handling
w.onlinejs.addEvent = function (obj, type, callback) {
if (window.attachEvent) {
obj.attachEvent('on' + type, callback);
} else {
obj.addEventListener(type, callback);
}
}
w.onlinejs.addEvent(w, 'load', function () {
w.onlinejs.fireHandlerDependOnStatus(w.onLine);
});
w.onlinejs.addEvent(w, 'online', function () {
window.onlinejs.logic.checkConnectionWithRequest(true);
})
w.onlinejs.addEvent(w, 'offline', function () {
window.onlinejs.logic.checkConnectionWithRequest(true);
})
w.onlinejs.getStatusFromNavigatorOnLine();
w.onlinejs.logic.init();
w.checkOnLine();
w.onlinejs.startCheck();
w.onlinejs.handlerFired = false;
})(window);
Looking at the source, I believe you can simply call onlinejs.logic.checkConnectionWithRequest(false) to get the status synchronously. This function will return either true or false.
PS: I am sure there are better libraries for this task out there, I really do not like the way it's written and clearly, the author doesn't know JS very well. E.g., the following code taken from the library makes no sense at all.
w.onlinejs.stopCheck = function () {
clearInterval("window.onlinejs.logic.checkConnectionWithRequest(true)", w.onLineCheckTimeout);
}
I hope that somebody can help me.
I want to redeclare js function by extension.
For example, there is the basic js function on website:
function foo(){
..something here..
}
i want to redeclare it by own function with the same name. how it will be easiest to do?
edit 1. i'll try to explain better.
there is a native code in website:
Notifier = {
debug: false,
init: function (options) {
curNotifier = extend({
q_events: [],
q_shown: [],
q_closed: [],
q_max: 3,
q_idle_max: 5,
done_events: {},
addQueues: curNotifier.addQueues || {},
recvClbks: curNotifier.recvClbks || {},
error_timeout: 1,
sound: new Sound('mp3/bb1'),
sound_im: new Sound('mp3/bb2')
}, options);
if (!this.initFrameTransport() && !this.initFlashTransport(options)) {
return false;
}
this.initIdleMan();
if (!(curNotifier.cont = ge('notifiers_wrap'))) {
bodyNode.insertBefore(curNotifier.cont = ce('div', {id: 'notifiers_wrap', className: 'fixed'}), ge('page_wrap'));
}
},
destroy: function () {
Notifier.hideAllEvents();
curNotifier.idle_manager.stop();
curNotifier = {};
re('notifiers_wrap');
re('queue_transport_wrap');
},
reinit: function () {
ajax.post('notifier.php?act=a_get_params', {}, {
onDone: function (options) {
if (options) {
curNotifier.error_timeout = 1;
this.init(options);
} else {
curNotifier.error_timeout = curNotifier.error_timeout || 1;
setTimeout(this.reinit.bind(this), curNotifier.error_timeout * 1000);
if (curNotifier.error_timeout < 256) {
curNotifier.error_timeout *= 2;
}
}
}.bind(this),
onFail: function () {
curNotifier.error_timeout = curNotifier.error_timeout || 1;
setTimeout(this.reinit.bind(this), curNotifier.error_timeout * 1000);
if (curNotifier.error_timeout < 256) {
curNotifier.error_timeout *= 2;
}
return true;
}.bind(this)
});
}
}
and function Sound
function Sound(filename) {
var audioObjSupport = false, audioTagSupport = false, self = this, ext;
if (!filename) throw 'Undefined filename';
try {
var audioObj = ce('audio');
audioObjSupport = !!(audioObj.canPlayType);
if (('no' != audioObj.canPlayType('audio/mpeg')) && ('' != audioObj.canPlayType('audio/mpeg')))
ext = '.mp3?1';
else if (('no' != audioObj.canPlayType('audio/ogg; codecs="vorbis"')) && ('' != audioObj.canPlayType('audio/ogg; codecs="vorbis"')))
ext = '.ogg?1';
else
audioObjSupport = false;
} catch (e) {}
// audioObjSupport = false;
if (audioObjSupport) {
audioObj.src = filename + ext;
var ended = false;
audioObj.addEventListener('ended', function(){ended = true;}, true);
audioObj.load();
this.playSound = function() {
if (ended) {
audioObj.load();
}
audioObj.play();
ended = false;
};
this.pauseSound = function() {
audioObj.pause();
};
} else {
cur.__sound_guid = cur.__sound_guid || 0;
var wrap = ge('flash_sounds_wrap') || utilsNode.appendChild(ce('span', {id: 'flash_sounds_wrap'})),
guid = 'flash_sound_' + (cur.__sound_guid++);
var opts = {
url: '/swf/audio_lite.swf?4',
id: guid
}
var params = {
swliveconnect: 'true',
allowscriptaccess: 'always',
wmode: 'opaque'
}
if (renderFlash(wrap, opts, params, {})) {
var swfObj = browser.msie ? window[guid] : document[guid],
inited = false,
checkLoadInt = setInterval(function () {
if (swfObj && swfObj.paused) {
try {
swfObj.setVolume(1);
swfObj.loadAudio(filename + ext);
swfObj.pauseAudio();
} catch (e) {debugLog(e);}
}
inited = true;
clearInterval(checkLoadInt);
}, 300);
self.playSound = function() {
if (!inited) return;
swfObj.playAudio(0);
};
self.pauseSound = function() {
if (!inited) return;
swfObj.pauseAudio();
};
}
}
}
Sound.prototype = {
play: function() {
try {this.playSound();} catch(e){}
},
pause: function() {
try {this.pauseSound();} catch(e){}
}
};
when i try to add injection with redeclaration function Sound it doesn't work.
if i create my own function, for example, xSound and сall it this way:
cur.sound = new xSound('mp3/bb1');
it's working.
You can do it like this, for example:
foo = function(args) {
// method body...
}
JavaScript is a programming language where functions are first-class citizens so you can manipulate them like other types.
UPDATE:
Make sure that this piece of code actually does the redefinition and not the first definition. (thanks to #jmort253)
function foo(){
// ..something else here..
}
Remember that an extension's Content Script code and the webpage code run in different execution contexts.
So if you want to redefine a function that exists in the webpage context, you'll have to inject your code into the webpage. Take a look at this answer by Rob W for different methods of doing that:
Insert code into the page context using a content script