I am developing a cross browser extension using kango framework. I want to add my extension to the context menu of the browser. I already have set "context_menu": true in the permissions array in extension_info.json file, but still my extension does not appear in the context menu ( when there is a right click in the browser window). How can I do this?
You need to add an event listener to main.js like this:
kango.ui.contextMenuItem.addEventListener(kango.ui.contextMenuItem.event.CLICK, function() {
kango.browser.tabs.getCurrent(function(tab) {
tab.dispatchMessage('ContextMenuItemClick');
});
});
And in the content.js you need to consume the event like this:
function handleContextMenuClick() {
var clickedElement = null;
if ('addEventListener' in document) {
document.addEventListener('mousedown', function(event) {
if (event.button == 2 && IsSupported()) {
clickedElement = event.target;
kango.console.log('StopIt menu item click 1');
}
}, true);
} else {
document.attachEvent('onmousedown', function(event) {
event = event || window.event;
if (event.button == 2&& IsSupported()) {
clickedElement = event.srcElement;
kango.console.log('StopIt menu item click 2');
}
});
}
kango.addMessageListener('ContextMenuItemClick', function(event) {
kango.console.log("addMessageListener: ContextMenuItemClick added");
});
}
handleContextMenuClick();
// Only activate the menu when the user is on facebook or twitter.
// This should be loaded from a service and updated one each new domain visited.
function IsSupported()
{
if(document.domain.indexOf("facebook.") > -1) return true;
if(document.domain.indexOf("twitter.") > -1) return true;
return false;
}
Related
Please help with the script function on how to make select2 plugin work in wizard jquery template it is not firing and i'm using the search box, when it clicked it jams.Thank you
$('.class').select2(); AFTER $('#form').steps();
This has helped me thanks but..
$("#form").steps({
bodyTag: "fieldset",
onStepChanging: function (event, currentIndex, newIndex)
{
// Always allow going backward even if the current step contains invalid fields!
if (currentIndex > newIndex)
{
return true;
}
// Forbid suppressing "Warning" step if the user is to young
if (newIndex === 3 && Number($("#age").val()) < 18)
{
return false;
}
var form = $(this);
// Clean up if user went backward before
if (currentIndex < newIndex)
{
// To remove error styles
$(".body:eq(" + newIndex + ") label.error", form).remove();
$(".body:eq(" + newIndex + ") .error", form).removeClass("error");
}
// Disable validation on fields that are disabled or hidden.
form.validate().settings.ignore = ":disabled,:hidden";
// Start validation; Prevent going forward if false
return form.valid();
},
onStepChanged: function (event, currentIndex, priorIndex)
{
// Suppress (skip) "Warning" step if the user is old enough.
if (currentIndex === 2 && Number($("#age").val()) >= 18)
{
$(this).steps("next");
}
// Suppress (skip) "Warning" step if the user is old enough and wants to the previous step.
if (currentIndex === 2 && priorIndex === 3)
{
$(this).steps("previous");
}
},
onFinishing: function (event, currentIndex)
{
var form = $(this);
// Disable validation on fields that are disabled.
// At this point it's recommended to do an overall check (mean ignoring only disabled fields)
form.validate().settings.ignore = ":disabled";
// Start validation; Prevent form submission if false
return form.valid();
},
onFinished: function (event, currentIndex)
{
var form = $(this);
// Submit form input
form.submit();
}
}).validate({
errorPlacement: function (error, element)
{
element.before(error);
},
rules: {
confirm: {
equalTo: "#password"
}
}
});
//IMPORTANT
var form =$("#form");
form.find("#personel_id").select2({
theme: 'bootstrap4',
});
I am trying to load 12 items only each time, until the user scroll all the way down and load another 12 elements
For some reason my code doesn't work. When i upload another item, i can see it in the admin panel so it is successfully uploaded but i can't see it in the normal user view. i can only view the first 12 items uploaded and it doesn't load anymore items when i scroll.
Here is my code in the client side
if (Meteor.isClient) {
var ITEMS_INCREMENT = 12; //this one refers to the number of elements to load
Session.setDefault('itemsLimit', ITEMS_INCREMENT);
Deps.autorun(function() {
Meteor.subscribe('items', Session.get('itemsLimit'));
});
Template.list_products.helpers({
applications: function () {
var limit = Session.get("itemsLimit");
//return Products.find({}, { sort: {createdAt: -1},limit: limit }); // render latest first
return Products.find({}, { sort: {createdAt: 1},limit: limit }); // render first first
}
});
Template.list_products.moreResults = function() {
// If, once the subscription is ready, we have less rows than we
// asked for, we've got all the rows in the collection.
return Products.find({}, { sort: {createdAt: -1},limit: limit });
}
// whenever #showMoreResults becomes visible, retrieve more results
function showMoreVisible() {
var threshold, target = $("#showMoreResults");
if (!target.length) return;
threshold = $(window).scrollTop() + $(window).height() - target.height();
if (target.offset().top < threshold) {
if (!target.data("visible")) {
// console.log("target became visible (inside viewable area)");
target.data("visible", true);
Session.set("itemsLimit",
Session.get("itemsLimit") + ITEMS_INCREMENT);
}
} else {
if (target.data("visible")) {
// console.log("target became invisible (below viewable arae)");
target.data("visible", false);
}
}
}
// The below line is to run the above func every time the user scrolls
$(window).scroll(showMoreVisible);
}
Here how i solved it:
if(Meteor.isClient) {
Session.set("itemsLimit", 9); // to set the limit to 9
lastScrollTop = 0;
$(window).scroll(function(event){
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) { // to detect scroll event
var scrollTop = $(this).scrollTop();
if(scrollTop > lastScrollTop){ // detect scroll down
Session.set("itemsLimit", Session.get("itemsLimit") + 9); // when it reaches the end, add another 9 elements
}
lastScrollTop = scrollTop;
}
});
}
It works like a charm now :)
You can implement it like this:
HTML File:
<template name="yourTemplateName">
<div id="divId">
{{#each dataArr}}
//your view here.
{{/each}}
</div>
{{#if noMoreItem}}
<span>No more items to show</span>
{{/if}}
</template>
JS File:
var pageNumber = new ReactiveVar(0);
var noMoreItem = new ReactiveVar(false);
var mainContainer = // Your element here example: document.getElementById('divId')
mainContainer.addEventListener('scroll', function(){
if(mainContainer.scrollHeight - mainContainer.scrollTop === mainContainer.clientHeight) {
getMoreItems();
}
});
var getMoreItems = function () {
if(pageNumber.get() < Math.floor(Counts.get('countItems')/12)) {
pageNumber.set(Number(pageNumber.get())+1);
Meteor.subscribe('pubName', pageNumber.get(), 12);
} else {
noMoreItem.set(true);
}
}
Template.yourTemplateName.rendered = function () {
pageNumber.set(0);
Meteor.subscribe('pubName', pageNumber.get(), 12);
}
Template.yourTemplateName.helpers({
'dataArr': function () {
return CollectionName.find();
},
'noMoreItem': function () {
return noMoreItem.get();
}
})
Publication:
Meteor.publish("pubName", function (pageNumber, pageSize) {
Counts.publish(this, 'countItems', Meteor.users.find(filter), {
noReady: true
});
return CollectionName.find({}, {
skip: pageNumber > 0 ? ((pageNumber) * pageSize) : 0,
limit: pageSize
})
});
Is it possible to hide events that are inside background events so that the user cannot see it?
if yes what is the way to do it ?
var isValidEvent = function(start,end,id){
return $("#calendar").fullCalendar('clientEvents', function (event) {
return (event.rendering === "background" && id!='test' &&
(start>event.start) && (end<event.end)) ;
}).length > 0;
};
eventRender:function(event, element, view) if(isValidEvent(event.start,event.end,event.id)){
$(element).hide();
},
As of the docs, eventRender callback should either return an event OR false if the event should be hidden:
eventRender:function(event, element, view)
if(isValidEvent(event.start,event.end,event.id)){
return event;
}
else {
return false;
}
},
I haven't tested yet as I don't need it, but should work that way.
I got it like this:
eventRender:function(event, element, view){
var array= new Array();
array = $("#calendar").fullCalendar('clientEvents','test');
for(i of array){
if(event.source.url=="events.php" && moment(event.start)>=moment(i.start) && moment(event.end)<=moment(i.end)){
return false;
}
} }
I would like to switch to an iframe using pure phantom.js code
Here is my first attempt
var page = new WebPage();
var url = 'http://www.theurltofectch'
page.open(url, function (status) {
if ('success' !== status) {
console.log("Error");
} else {
page.switchToFrame("thenameoftheiframe");
console.log(page.content);
phantom.exit();
}
});
It produces only the source code of the main page. Any idea ?
Notice that the iframe domain is different from the main page domain.
Please give this a try I believe it may be an async issues meaning the iframe is not present when trying to access it. I received the below snippet from another post.
var page = require('webpage').create(),
testindex = 0,
loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
/*
page.onNavigationRequested = function(url, type, willNavigate, main) {
console.log('Trying to navigate to: ' + url);
console.log('Caused by: ' + type);
console.log('Will actually navigate: ' + willNavigate);
console.log('Sent from the page\'s main frame: ' + main);
};
*/
/*
The steps array represents a finite set of steps in order to perform the unit test
*/
var steps = [
function() {
//Load Login Page
page.open("https://www.yourpage.com");
},
function() {
//access your iframe here
page.evaluate(function() {
});
},
function() {
//any other step you want
page.evaluate(function() {
});
},
function() {
// Output content of page to stdout after form has been submitted
page.evaluate(function() {
//console.log(document.querySelectorAll('html')[0].outerHTML);
});
//render a test image to see if login passed
page.render('test.png');
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] === "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] !== "function") {
console.log("test complete!");
phantom.exit();
}
}, 50);
replace
console.log(page.content);
with
console.log(page.frameContent);
Should return the contents of the frame phantomjs switched to.
If the iframe is from another domain you may need to add the --web-security=no option like this:
phantomjs --web-security=no myscript.js
As an additional information, what xMythicx said could be true. Some iframes are rendered via Javascript after page finishes loading. If the iframe contents are empty, then you will need to wait for all resources to finish loading, before you start grabbing stuff from the page. But this is another issue, if you need an answer on this, I suggest you ask a new question about it, and I will answer there.
Had the same problem for iframes and
phantomjs --web-security=no
helped in my case :]
I am using Update Panel in my asp page and I am doing JQuery Validation on Asynchronous Postback...
I just want to validate my form on only button clicks or submits...
My problem is..all my buttons are in different formviews and won't load at a time...that's why I am unable to take the button id's and use the click events..here is my code..
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(ValidateMyForm);
function ValidateMyForm(sender, args) {
var objPost = args.get_postBackElement();
if (objPost === null || objPost === undefined) return;
if (objPost.id == '<%= ((Button)(formViewinfo.FindControl("btnUpdate"))).ClientID %>') {
$('#pnlerrors').fadeOut('fast');
$('#pnlItemErrors').fadeOut('fast');
var isValid = $('#form1').validate({
errorClass: 'error',
invalidHandler: function (e, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#pnlerrors').html('<p> Please correct the errors </p>').fadeIn('fast');
document.location.href = '#pnlerrors';
}
}, submitHandler: function () {
}
}).form();
if (!isValid) {
CancelPostback(sender, args);
} else {
}
}
//this is for rest of buttons
else {
$('#pnlItemErrors').fadeOut('fast');
$('#pnlerrors').fadeOut('fast');
var isValid = $('#form1').validate({
errorClass: 'error',
invalidHandler: function (e, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#pnlerrors').fadeOut('fast');
document.location.replace('#', '#pnlItemErrors');
$('#pnlItemErrors').html('<p> Please correct the errors </p>').fadeIn('fast');
document.location.href = '#pnlItemErrors';
}
}, submitHandler: function () {
}
}).form();
if (!isValid) {
CancelPostback(sender, args);
} else {
}
}
}
All I want to do is: 2nd time validation on only button submit not for everything...I do get other postbacks on this page and those post backs also gets validated each time (I want to Avoid this)...
I don't know this approach is good or not...I am struggling with this from long time..I really appreciate you help...
On the assumption that you don't want to submit the form when someone presses the enter button, and that you only want to submit the form on pressing a submit button:
$(document).ready(
function(){
$('form').keypress(
function(event){
if (event.keyCode == '13'){
return false;
}
});
$('input:submit').click(
function(){
$(this).closest('form').submit();
});
$('form').submit(
function(){
$('#success').text('form submitted! (Not really...)');
return false;
// Just to stop the error messages
// in this demo.
});
});
There's a JS Fiddle demo, here: http://jsfiddle.net/davidThomas/5PaWz/.
If I'm mistaken in my assumptions, please leave a comment and I'll try to correct myself.
if your problem is just about finding the buttons the need to have validations then
one way of getting around this is to add a class to the buttons that you want to trigger validation, for example :
<asp:button id="btn1" cssclass="Validate"/>
then you can grab all these buttons in JQuery:
var buttons = $('.Validate');
get each button id:
$(buttons).each(function(){
var id = this.id;
});
ohh..god finally found the solution for my problem...First of all my apologizes if my question is not clear....
My validation works on asynchronous post backs...I just want validate my form on button clicks..i do have an asp.net grid view in my page..if i click on paging or something on the grid it fires validation...i want avoid this..
for this what i did is...i am capturing the postback element with the following statement.
var objPost = args.get_postBackElement();
then i am checking for type..
if (objpost.type == 'submit') { do validation }
else { don't }..
this ends my 2days struggle...
thank you very much your support and help...
Try different approach.
Use asp.Net Button with UseSubmitBehavior=true for submission
and use asp.Net Button with UserSubmitBehavior=false for buttons that you don't want them to fire the validation process that. add this following code to your form
function ValidateForm()
{
var errors ="";
if (typeof(Page_ClientValidate) == 'function')
{
if (typeof (Page_ClientValidate) == 'function') { Page_ClientValidate(); }
if (!Page_IsValid)
{
for (i = 0; i < Page_Validators.length; i++) {
var inputControl = document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
errors = errors + ";" + Page_Validators[i].errormessage;
inputControl.style.border ="solid 2px #FF0000";
}
}
}
return Page_IsValid;
}
return true;
}
$(document).ready(function(){
/*********************************************************************/
///handle form submittion and run validation prior to that
///if a textbox has required field validator, stop form submittion and
/// highlight the text box
/*********************************************************************/
$('#form1').submit(function(){
return ValidateForm();
});