extjs 5 window not executing javascript - extjs5

I have the following function that creates a extjs window. Within the php page is some javascript (for now just a alert("test")) But the alert fails to fire. My understanding is that setting scripts to true should execute script tags.
function loadTilePage(tileId){
var url= "page.php";
var yourWindow = new Ext.Window({
title: 'title',
autoScroll: true,
resizable :false,
height:Ext.getBody().getViewSize().height*.60,
width:Ext.getBody().getViewSize().width*0.55,
loader:{
url:url,
scripts: true,
renderer: 'html',
autoLoad: true
}
});
yourWindow.show();
yourWindow.center();
}
In the end of the php response is this:
<script type="text/javascript">
alert("test");</script>

Injecting script into element markup is blocked by browser. Example:
document.getElementById('div').innerHTML = '<scr' + 'ipt>alert(123);</scr' + 'ipt>'; // this won't work
Fiddle: http://jsfiddle.net/g3dahakr/
You should probably find other way to do that. In Ext JS you can require other JS modules, so IMO instead of using loader it is better to replace page.php with Ext component and load it using require.

Related

How to disable js Minification in gulp when using npm gulp-minify-inline plugin

Am using gulp-minify-inline plugin to only compress inline javascript and css for sales force pages and component which is basally html code.
Am trying to disable the js minification via option. Could any one suggest what attribute i need it as false?
Plugin url: https://www.npmjs.com/package/gulp-minify-inline
Document: https://github.com/terser/terser
var minifyInline = require('gulp-minify-inline');
var options = {
js: {
output: {
comments: true
},
minify: false -----> Not working
},
jsSelector: 'script[type!="text/x-handlebars-template"]',
css: {
level: {1: {specialComments: 0}}
},
cssSelector: 'style[data-do-not-minify!="true"]'
};
gulp.task('minify-inline', function() {
gulp.src('src/*.html')
.pipe(minifyInline(options))
.pipe(gulp.dest('dist/'))
});
js contains parameters to pass to terser.minify() (for documetation refer to the project homepage). Set it to false to disable JS minification globally
You might try js: false

Inject HTML into a page from a content script

I am building a Chrome Extension and I have a requirement to overlay a blob of html on top of a few websites. At the moment I am using a JQuery .Get to pull the html from my server. In order to improve performance I am wondering if it is possible to include the html as a file in the extension directory and access the source directly from there? Does anyone know if this is possible?
UPDATE
Rob's suggestion does the job (see accepted answer). The only additional step is to register the file in the manifest under web_accessible_resources.
{
...
"web_accessible_resources": [
"myimportfile1.html",
"myimportfile2.html"
],
...
}
Yes, that's possible. Use chrome.runtime.getURL to get an absolute URL for the resource. For example:
Step 1 (standard JavaScript):
fetch(chrome.runtime.getURL('/template.html')).then(r => r.text()).then(html => {
document.body.insertAdjacentHTML('beforeend', html);
// not using innerHTML as it would break js event listeners of the page
});
Step 1 (jQuery):
$.get(chrome.runtime.getURL('/template.html'), function(data) {
$(data).appendTo('body');
// Or if you're using jQuery 1.8+:
// $($.parseHTML(data)).appendTo('body');
});
Step 2:
Register the resource in the manifest.json under web_accessible_resources:
"web_accessible_resources": [
"template.html",
"foo.jpg"
]
Another way of doing it is to use new Fetch API:
If the file's name is modal.html - update manifest.json accordingly
"web_accessible_resources": [
"modal.html",
],
and inject it like this:
fetch(chrome.runtime.getURL('/modal.html'))
.then(response => response.text())
.then(data => {
document.getElementById('inject-container').innerHTML = data;
// other code
// eg update injected elements,
// add event listeners or logic to connect to other parts of the app
}).catch(err => {
// handle error
});
This is my approach using a synchronous XHR:
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", chrome.runtime.getURL ("src/inject/inject.html"), false );
xmlHttp.send( null );
var inject = document.createElement("div");
inject.innerHTML = xmlHttp.responseText
document.body.insertBefore (inject, document.body.firstChild);
Without jQuery etc.
I use this code. It's only 3 lines of code and you don't need any jquery's garbage.
var iframe = document.createElement ('iframe');
iframe.src = chrome.runtime.getURL ('iframe.html');
document.body.appendChild (iframe);
If you're using Angular in your Chrome extension, you can make use of ng-include
var injectedContent = document.createElement("div");
injectedContent.setAttribute("ng-include", "");
//ng-include src value must be wrapped in single quotes
injectedContent.setAttribute("src", "'" + chrome.runtime.getURL("template.html") + "'");
existingElement.appendChild(injectedContent);

How to show html files with modal.open using jquery?

Currently i use a fine working code for opening a modal with Jquery :
$(document).ready(function(){
$("span.ico-detail").click(function(){
modal.open({content: "View detail of " + $(this).parent().parent().attr("id")});
e.preventDefault();
});
});
And now the problem is : How can I use modal.open to open a HTML file named "view.html", which contaning the string of "View detail of "?
What should I change the content : "xxx" with, so I can open the HTML file (view.html) and join it with other text ?
Thanks before.
If the view.html is stored on a server and its content is static, then you can choose to preload the content of the file using ajax.
$(function () {
window.myAppNs = {
viewContent: null;
};
$.ajax({
url: 'view.html',
dataType: 'html',
type: 'GET'
}).done(function (resp) {
myAppNs.viewContent = resp;
});
$("span.ico-detail").click(function(){
modal.open({content: myAppNs.viewContent + $(this).parent().parent().attr("id")});
e.preventDefault();
});
});
I am creating a global variable myAppNs. This will hold all app related variables. The idea is not pollute the global namespace with unnecessary variables. There are better and safer ways to create a namespace. If that interests you, you can google for the same.
The ajax call preloads the content of the view.html and stores it in myAppNs.viewContent. The click handler reads that content from the variable.
There is a slight chance that the user can click the element before the ajax response is returned. If that's an issue, you can always move the namespace creation and ajax call out of document.ready and place it in the head section, immediately after referencing jquery. That ought to give the browser enough time to fetch the content before the dom is ready, but there is still that small possibility that the response might be delayed. If you need to ensure the user can click only if the data has been fetched, then bind the click handler inside the done callback of the ajax call.

Uploading Image (Local) to Tinymce

I would like to ask if there is any plugin available that is able to upload image from my local system to tinymce? Tinymce has an image upload but for online images. Furthermore, the uploading of images from local system is an advanced feature of tinymce, needs to be bought. So, is there a free plugin I can use to integrate uploading of images from local system to tinymce? Thanks! :)
You could write an own plugin and insert your images as a base64-encoded string.
Example: You will need to fetch a javascript function from the web and create the string my_image_base64_string (already given here). The snippet shows howto insert the image afterwards. Using an own plugin you will be able to create a button and use for example a popup.
var my_image_base64_string = 'R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';
tinymce.activeEditor.execCommand('insertHTML', false, '<img src="data:image/gif;base64,' + my_image_base64_string + '" width="16" height="14">');
I have created a plugin on Github Which allow you to upload image and as a embed , after that image will automatically converted to Base64 data string the plugin is found on the link below:
https://github.com/buddyexpress/bdesk_photo
You can create custom button:
tinymce.init({
selector: `#${this.props.id}`,
...
toolbar: '... uploadimage ...',
paste_data_images: true,
setup:
...
editor.addButton('uploadimage', {
text: '',
icon: 'image',
onclick: this.uploadImage,
});
},
})
And uploadImage function:
uploadImage() {
var editor = tinymce.activeEditor;
// create input element, call modal dialog w
var fileInput = document.createElement('input');
fileInput.setAttribute('type', 'file');
fileInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
// if file is submitted run our key code
fileInput.addEventListener('change', () => {
if (fileInput.files != null && fileInput.files[0] != null) {
// create instance of FileReader()
let reader = new FileReader();
// create event triggered after successful reading operation
reader.onload = (e) => {
// insert content in TinyMCE
editor.insertContent('<img src="' + e.target.result + '">');
fileInput.value = '';
};
reader.readAsDataURL(fileInput.files[0]);
}
});
fileInput.click()
}
After this you should see your base64 image in the editor.

Using jQuery.getJSON in Chrome Extension

I need to do a cross-domain request in a chrome extension. I know I can it via message passing but I'd rather stick to just jQuery idioms (so my javascript can also work as a <script src="">).
I do the normal:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) {
console.log(data);
});
but in the error console I see:
Uncaught ReferenceError: jsonp1271044791817 is not defined
Is jQuery not inserting the callback function correctly into the document? What can I do to make this work?
(If I paste the code into a chrome console, it works fine, but if I put it as the page.js in an extension is when the problem appears.)
Alas, none of these worked, so I ended up doing the communication via the background.html.
background.html
<script src="http://code.jquery.com/jquery-1.4.2.js"></script>
<script>
function onRequest(request, sender, callback) {
if (request.action == 'getJSON') {
$.getJSON(request.url, callback);
}
}
chrome.extension.onRequest.addListener(onRequest);
</script>
javascripts/page.js
chrome_getJSON = function(url, callback) {
console.log("sending RPC");
chrome.extension.sendRequest({action:'getJSON',url:url}, callback);
}
$(function(){
// use chrome_getJSON instead of $.getJSON
});
If you specify "api.flickr.com" in your manifest.json file you will not need to use the JSONP callback, script injection style of cross domain request.
For example:
"permissions": ["http://api.flickr.com"],
This should work beautifully in you code. I would remove the querystring parameter "&jsoncallback" as there is no JSONP work needed.
The reason why your current code is not working is your code is injecting into pages DOM, content scripts have access to the DOM but no access to javascript context, so there is no method to call on callback.
My impressions it that this fails because the jQuery callback function is being created within the 'isolated world' of the Chrome extension and is inaccessible when the response comes back:
http://code.google.com/chrome/extensions/content_scripts.html#execution-environment
I'm using Prototype and jQuery for various reasons, but my quick fix should be easy to parse:
// Add the callback function to the page
s = new Element('script').update("function boom(e){console.log(e);}");
$$('body')[0].insert(s);
// Tell jQuery which method to call in the response
function shrink_link(oldLink, callback){
jQuery.ajax({
type: "POST",
url: "http://api.awe.sm/url.json",
data: {
v: 3,
url: oldLink,
key: "5c8b1a212434c2153c2f2c2f2c765a36140add243bf6eae876345f8fd11045d9",
tool: "mKU7uN",
channel: "twitter"
},
dataType: "jsonp",
jsonpCallback: callback
});
}
// And make it so.
shrink_link('http://www.google.com', "boom");
Alternatively you can try using the extension XHR capability:
http://code.google.com/chrome/extensions/xhr.html
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// JSON.parse does not evaluate the attacker's scripts.
var resp = JSON.parse(xhr.responseText);
}
}
xhr.send();
The syntax is a little off. There's no need for the callback( bit. This works flawlessly. Tested in the javascript console of Chrome on this StackOverflow page (which includes jQuery):
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) {
console.log(data);
});
As many of you will know, Google Chrome doesn't support any of the handy GM_ functions at the moment.
As such, it is impossible to do cross site AJAX requests due to various sandbox restrictions (even using great tools like James Padolsey's Cross Domain Request Script)
I needed a way for users to know when my Greasemonkey script had been updated in Chrome (since Chrome doesn't do that either...). I came up with a solution which is documented here (and in use in my Lighthouse++ script) and worth a read for those of you wanting to version check your scripts:
http://blog.bandit.co.nz/post/1048347342/version-check-chrome-greasemonkey-script