Here is the script:
<script type="text/javascript">
// <![CDATA[
$(document).ready(function() {
$('#file_upload').uploadify({
'uploader' : '/uploadify/uploadify.swf',
'script' : '/upload2.php',
'cancelImg' : '/uploadify/cancel.png',
'folder' : '/uploads',
'auto' : false,
'onError' : function (event,ID,fileObj,errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
},
'fileExt' : '*.wma;*.mp3',
'fileDesc' : 'Audio Files',
'scriptData' : {'fileID':'20541','hash':'2e1177c09a6503d11b1a401177022de50409e96279a2dbb11c5aef5783d231c975da22e2ddfd480b5e050f4fb09d9b7caa47a71ab0150b7c462b06d06e61e664','hashit':'fe458d423c6d1c18248b73dad776a9d4a6ff1ac9fc4b07674b3715b4992a80b9d2b4e3a340973642497d66ac8e8d57d7aa737f8911a784888b164e84961f177a'},
'onComplete' : function(eventID,ID,fileObj,response,data) {
window.location = "http://www.messageshare.com/welcome/file_farm/20541/fe458d423c6d1c18248b73dad776a9d4a6ff1ac9fc4b07674b3715b4992a80b9d2b4e3a340973642497d66ac8e8d57d7aa737f8911a784888b164e84961f177a";
}
});
});
// ]]>
</script>
I need to change 'auto' from false to true.
Since all those scriptData values seem liable to change from page load to page load, what you'd want to do is intercept that <script> node on the fly, clone it and only change 'auto' to true, using RegEx.
On Firefox Greasemonkey, you can do that with the stupefyingly brilliant (^_^) checkForBadJavascripts utility. Like so:
// ==UserScript==
// #name _Modify JS as it's loaded
// #include http://YOUR_SERVER.COM/YOUR_PATH/*
// #require https://gist.github.com/raw/2620135/checkForBadJavascripts.js
// #run-at document-start
// #grant GM_addStyle
// ==/UserScript==
/*- The #grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
function replaceTargetJavascript (scriptNode) {
var scriptSrc = scriptNode.textContent;
scriptSrc = scriptSrc.replace (
/'auto'\s+\:\s+false/,
"'auto' : true"
);
addJS_Node (scriptSrc);
}
checkForBadJavascripts ( [
[false, /'auto'\s+\:\s+false/, replaceTargetJavascript]
] );
Related
I'm new to electron, a piece of code in the electron tutorial code puzzles me, it should be simple, but I did not find any documentation or article that explains why it's possible.
With context isolation enabled, it is possible to update DOM by setting innerText property of an element.
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
It seems impossible to me because Electron documentation says
parameters, errors and return values are copied when they are sent over the bridge
To find out why, I tried to expose a function setElementText into the "main world".
// preload.js
const {contextBridge} = require('electron')
// ...
contextBridge.exposeInMainWorld('bridgeTest', {
setElementText: (element, text) => {
window.abc = 123 // executed in isolated world, won't work
element.innerText = text
}
})
In render.js, call exposed function setElementText.
Execution of this function is proxied so that the body of the function is executed in the "isolated world", I know it because trying to set window.abc, but later in devtools of the window, console.log(window.abc) prints undefined.
Also, if a normal object is passed to setElementText, its innerText property remain unchanged, a similar function setElementText2 defined in the "main world" can change innerText property of the same object.
const setElementText2 = (element, text) => {
element.innerText = text
}
window.addEventListener('DOMContentLoaded', () => {
window.def = 456 // executed in the main world, works
const o = {innerText: 'xyz'}
window.bridgeTest.setElementText(o, 'xxyyzz')
console.log(o.innerText) // xyz
setElementText2(o, 'aabbcc')
console.log(o.innerText) // aabbcc
})
If a DOM element is passed to the exposed setElementText, its innerText property does change, so does the DOM content
window.addEventListener('DOMContentLoaded', () => {
window.def = 456 // executed in main world, works
const helloElement = document.getElementById('hello')
window.bridgeTest.setElementText(
helloElement, 'Hello World')
console.log(helloElement.innerText) // Hello World
})
All source code:
main.js
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
preload.js
const {contextBridge} = require('electron')
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
contextBridge.exposeInMainWorld('bridgeTest', {
setElementText: (element, text) => {
window.abc = 123 // executed in isolated world, won't work
element.innerText = text
}
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
<link href="./styles.css" rel="stylesheet">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
<p id="hello">abcdefg</p>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>
render.js
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// No Node.js APIs are available in this process because
// `nodeIntegration` is turned off. Use `preload.js` to
// selectively enable features needed in the rendering
// process.
const setElementText2 = (element, text) => {
element.innerText = text
}
window.addEventListener('DOMContentLoaded', () => {
const helloElement = document.getElementById('hello')
window.def = 456 // executed in main world, works
window.bridgeTest.setElementText(
helloElement, 'Hello World')
console.log(helloElement.innerText) // Hello World
const o = {innerText: 'xyz'}
window.bridgeTest.setElementText(o, 'xxyyzz')
console.log(o.innerText) // xyz
setElementText2(o, 'aabbcc')
console.log(o.innerText) // aabbcc
})
style.css
/* styles.css */
/* Add styles here to customize the appearance of your app */
$("#ddl").change(function () {
var strSelected = "";
$("#ddl option:selected").each(function () {
strSelected += $(this)[0].value;
});
if (strSelected.length != 0) {
var url = "/Reseller/MailPartial/?resellerId=" + strSelected;
$("#mail").empty();
$("#mail").load(url);
}
this is code I use to load partial in my View (partial is only 1 label and 1 editorfor,the one that should load tinymce). I have [UIHint("tinymce_jquery_full"), AllowHtml] in my model and tinymce editor loads perfectly normal in other views. But when I use partial views it comes back as plain text area. How to fix this?
thanks
EDIT:
I figured it out,ijaz was almost correct ;)
I needed to reinit tinymce like ijaz said but even when I called INitTinyMCE like ijaz said it wouldn't have mattered because the element hasn't loaded yet to html and I have no idea why. Solution was to call initTinyMce after the element has loaded to the page.
I tried to use
$("#mail").load(url, InitTinyMCE());
but it didn't work.
Any ideas how to call InitTinyMCE() after the element has loaded? It's working now but it's relying on pressing another button to trigger InitTinyMCE()
EDIT again
I changed code to pure ajax,no more .load()
sorry for being so messy :)
In the above code,it seems that [UIHint] is not applied properly. so get things work, kindly initialize the TinyMCE manualy, i mean change you code as ,
$("#ddl").change(function () {
var strSelected = "";
$("#ddl option:selected").each(function () {
strSelected += $(this)[0].value;
});
if (strSelected.length != 0) {
var url = "/Reseller/MailPartial/?resellerId=" + strSelected;
$("#mail").empty();
$("#mail").load(url);
**Re-Init TinyMCE**
InitTinyMCE();
}
function InitTinyMCE()
{
$('##ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty)').tinymce({
// Location of TinyMCE script
script_url: '#Url.Content("~/Scripts/tinymce/tiny_mce.js")',
theme: "advanced",
height: "170",
width: "240",
verify_html : false,
plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave",
// Theme options
theme_advanced_buttons1: "undo, redo,pasteword,|, bold, italic, underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,image, emotions" ,
theme_advanced_buttons2: "charmap, bullist, numlist,|,formatselect,fontselect,fontsizeselectcode, |,tiny_mce_wiris_formulaEditor, fullscreen",
theme_advanced_buttons3: "",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
// Example content CSS (should be your site CSS)
content_css : "#Url.Content("~/Scripts/tinymce/css/content.css")",
convert_urls : false,
// Drop lists for link/image/media/template dialogs
template_external_list_url : "lists/template_list.js",
external_link_list_url : "lists/link_list.js",
external_image_list_url : "lists/image_list.js",
media_external_list_url : "lists/media_list.js"
});
}
I tried putting the following code into a html and ran it and I uploaded it in my server and opened the link in my Safari browser in my iPhone and the clicked on Show Confirm and no window popups up! Can someone please help.
<!DOCTYPE html>
<html>
<head>
<title>Notification Example</title>
<script type="text/javascript" charset="utf-8" src="http://mobile-web-development-with-phonegap.eclipselabs.org.codespot.com/svn-history/r99/trunk/com.mds.apg/resources/phonegap/js/phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
// Empty
}
// process the confirmation dialog result
function onConfirm(button) {
alert('You selected button ' + button);
}
// Show a custom confirmation dialog
function showConfirm() {
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
'Restart,Exit' // buttonLabels
);
}
</script>
</head>
<body>
<p>Show Confirm</p>
</body>
</html>
The code that you are using (navigator.notification.confirm) is specifically for the mobile platform that is it is meant to run within the PhoneGap mobile application. If you would like to test out the dialogs/confirm messages on a browser before compiling it into an application, I would suggest using a hybrid approach that detects the environment of the application and uses either the native confirm(message) or the PhoneGap specific Notification API. Below is an example Object that has been working for me:
/**
* The object encapsulates messaging functionality to work both in PhoneGap and
* browser environment.
* #author Zorayr Khalapyan
*
*/
var MessageDialogController = (function () {
var that = {};
/**
* Invokes the method 'fun' if it is a valid function. In case the function
* method is null, or undefined then the error will be silently ignored.
*
* #param fun the name of the function to be invoked.
* #param args the arguments to pass to the callback function.
*/
var invoke = function( fun, args ) {
if( fun && typeof fun === 'function' ) {
fun( args );
}
};
that.showMessage = function( message, callback, title, buttonName ) {
title = title || "DEFAULT_TITLE";
buttonName = buttonName || 'OK';
if( navigator.notification && navigator.notification.alert ) {
navigator.notification.alert(
message, // message
callback, // callback
title, // title
buttonName // buttonName
);
} else {
alert( message );
invoke( callback );
}
};
that.showConfirm = function( message, callback, buttonLabels, title ) {
//Set default values if not specified by the user.
buttonLabels = buttonLabels || 'OK,Cancel';
var buttonList = buttonLabels.split(',');
title = title || "DEFAULT TITLE";
//Use Cordova version of the confirm box if possible.
if (navigator.notification && navigator.notification.confirm) {
var _callback = function (index) {
if ( callback ) {
//The ordering of the buttons are different on iOS vs. Android.
if(navigator.userAgent.match(/(iPhone|iPod|iPad)/)) {
index = buttonList.length - index;
}
callback( index == 1 );
}
};
navigator.notification.confirm(
message, // message
_callback, // callback
title, // title
buttonLabels // buttonName
);
//Default to the usual JS confirm method.
} else {
invoke( callback, confirm( message ) );
}
};
return that;
})();
Hope this helps! Let me know if you have any questions.
I've seen many questions regarding context-menu and two-way communication and it appears that I know the answer to my question... "you can't", but I'm going to try anyway.
On each page there is a modal div that is created by a page-mod. This modal is designed to show up when a user hovers over words in text nodes to give a translation of the word. This works perfectly and I don't have any problems with the page-mod.
What I want to do now is allow the user to highlight a selection of text, right click to bring up the context menu where my new menu item will be to "Translate Selection", and then display the selection in the modal div. Here's where the problems begin. I can respond to the context and click events in the content script, which is fine if I didn't have to do a translation. The translation is done by a web service and the content script cannot call a web service because the callbacks don't exist in the context of the content script because it is in a proxy sandbox. That means that all web service calls need to come from main.js (this is how it works in the page-mod). The problem is that the context-menu object in main.js does not have access to the DOM to update the content of the modal div and show it, and it cannot send information to the content script so that the content script can update the DOM and show the modal div. So how do I get the translation to the DOM from the add-on script for the context-menu?
Is what I want to do possible with the SDK, or do I have to undo many hours of work to put my project back into the "old school" way of doing things so I can get the context menu to work correctly?
This is what I have (the page-mod works, need help with the context-menu):
exports.main = function (options, callbacks) {
'use strict';
var myAppMenuItem,
myAppContextMenu,
myAppPanel,
myAppMod,
self = require('self'),
contextMenu = require('context-menu');
myAppMenuItem = require('menuitems').Menuitem();
if (myAppMenuItem.getAttribute('checked') === 'false') {
return;
}
myAppMod = require('page-mod');
myAppMod.PageMod({
include: '*',
contentScriptWhen: 'ready',
contentScriptFile: [self.data.url('jquery-1.7.2.min.js'), self.data.url('myAppmod.js')],
contentStyleFile: self.data.url('myAppmod.css'),
onAttach: function (worker) {
worker.port.on(
'translate',
function (data) {
require('request')
.Request({
url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
content: {
appid : 'myappid',
to : data.to,
from : data.from,
text : data.text
},
onComplete: function (response) {
worker.port.emit('translation', { response : response.text, elementId : data.elementId });
}
})
.get();
}
);
}
});
myAppContextMenu = contextMenu.Item({
label: "Translate Selection",
context: contextMenu.SelectionContext(),
contentScriptFile : [self.data.url('jquery-1.7.2.min.js'), self.data.url('myAppcontextmenu.js')],
onMessage: function (data) {
require('request')
.Request({
url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
content: {
appid : 'myappid',
to : data.to,
from : data.from,
text : data.text
},
onComplete: function (response) {
<what can I do here to send the information to the content script?>
}
})
.get();
}
});
};
Thank you to Wladimir! The following code does what I want it to:
In the main.js for the context-menu:
myAppContextMenu = contextMenu.Item({
label: "Translate Selection",
context: contextMenu.SelectionContext(),
contentScriptFile : [self.data.url('jquery-1.7.2.min.js'), self.data.url('myAppcontextmenu.js')],
onMessage: function (data) {
var text = require('selection').text;
require('request')
.Request({
url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
content: {
appid : 'myappid',
to : data.to,
from : data.from,
text : text
},
onComplete: function (response) {
var index,
tabs = require('sdk/tabs');
for (index = 0; index < workers.length; index += 1) {
if (workers[index].tab === tabs.activeTab) {
workers[index].port.emit('selectionTranslation', { text: text, response : response.text, leftOffset : data.leftOffset, topOffset : data.topOffset });
}
}
}
})
.get();
}
});
and in the content script:
self.on(
'click',
function (node, data) {
'use strict';
var selectedElement = $(node),
messageData =
{
to : 'es',
from : 'en',
topOffset : selectedElement.offset().top + (selectedElement.height() / 2),
leftOffset : selectedElement.offset().left + (selectedElement.width() / 2)
};
self.postMessage(messageData);
}
);
There is a global workers array variable defined in the exports.main function that gets populated by the onAttach function of the page mod as so:
workers.push(worker);
worker.on(
'detach',
function () {
var index = workers.indexOf(worker);
if (index >= 0) {
workers.splice(index, 1);
}
}
);
I want to make "jQuery UI TAB" blink (like notification).
I have diffrent tabs (Inbox | Sent | Important). My timer function checks if there is a new message in inbox, if so, I want the Inbox tab to start blinking/ flashing unless its clicked open.
Have tried diffrent options like .effect(..), .tabs(fx: {..}) but nothing seems to work :(
Any idea if its possible or not?
Yes it's definitely possible.
To give me some practice, I've written a jQuery blinker plugin for you:
jQuery:
(function($){
// **********************************
// ***** Start: Private Members *****
var pluginName = 'blinker';
var blinkMain = function(data){
var that = this;
this.css(data.settings.css_1);
clearTimeout(data.timeout);
data.timeout = setTimeout(function(){
that.css(data.settings.css_0);
}, data.settings.cycle * data.settings.ratio);
};
// ***** Fin: Private Members *****
// ********************************
// *********************************
// ***** Start: Public Methods *****
var methods = {
init : function(options) {
//"this" is a jquery object on which this plugin has been invoked.
return this.each(function(index){
var $this = $(this);
var data = $this.data(pluginName);
// If the plugin hasn't been initialized yet
if (!data){
var settings = {
css_0: {
color: $this.css('color'),
backgroundColor: $this.css('backgroundColor')
},
css_1: {
color: '#000',
backgroundColor: '#F90'
},
cycle: 2000,
ratio: 0.5
};
if(options) { $.extend(true, settings, options); }
$this.data(pluginName, {
target : $this,
settings: settings,
interval: null,
timeout: null,
blinking: false
});
}
});
},
start: function(){
return this.each(function(index){
var $this = $(this);
var data = $this.data(pluginName);
if(!data.blinking){
blinkMain.call($this, data);
data.interval = setInterval(function(){
blinkMain.call($this, data);
}, data.settings.cycle);
data.blinking = true;
}
});
},
stop: function(){
return this.each(function(index){
var $this = $(this);
var data = $this.data(pluginName);
clearInterval(data.interval);
clearTimeout(data.timeout);
data.blinking = false;
this.style = '';
});
}
};
// ***** Fin: Public Methods *****
// *******************************
// *****************************
// ***** Start: Supervisor *****
$.fn[pluginName] = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || !method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist in jQuery.' + pluginName );
}
};
// ***** Fin: Supervisor *****
// ***************************
})( jQuery );
See it in action here
The plugin and the fiddle are pretty raw in that I haven't tried to integrate with jQuery-ui-tabs. This may be easy or hard, I don't know, but providing each tab is addressable by class or id then it shouldn't be too difficult.
Something you may need to consider is stopping a blinking tab when it is clicked. For this you may wish to call the .blinker('stop') method directly (with a .on('click') handler) or from an appropriate jQuery-ui-tabs callback.
API
The plugin is properly written in jQuery's preferred pattern. It puts just one member in the jQuery.fn namespace and .blinker(...) will chain like standard jQuery methods.
Methods :
.blinker('init' [,options]) : Initialises selected element(s) with blinker behaviour. Called automatically with .blinker(options), or just .blinker() in its simplest form.
.blinker('start') : causes selected element(s) to start blinking between two styles as determined by plugin defaults and/or options.
.blinker('stop') : causes selected element(s) to stop blinking and return to their natural CSS style(s).
Options : a map of properties, which determine blinker styles and timing:
css_0 : (optional) a map of css properties representing the blink OFF-state.
css_1 : a map of CSS properties representing the blink ON-state.
cycle : the blink cycle time in milliseconds (default 2000).
ratio : ON time as a proportion of cycle time (default 0.5).
By omitting css_0 from the options map, the OFF state is determined by the element(s)' natural CSS styling defined elsewhere (typically in a stylesheet).
Default values are hard-coded for css_1.color, css_1.backgroundColor, cycle time and ratio. Changing the default settings programmatically is not handled, so for different default styling the plugin will need to be edited.
jQuery comes by default with a slew of effects to pick from. You can easily use them wherever you see the need for them and they can be applied like so:
$('#newmsg').effect("pulsate", {}, 1000);
Demo
yes... this is what you need...!!!
this is javascript
if(newmessage==true){
$('#chat-86de45de47-tab').effect("pulsate", {}, 1000);
}
i think it's