I am trying to force XULRunner to ignore X-Frame-Options and bypass the security warning preventing the page from loading inside an iframe.
This is what I have come up with but it doesn't work.
function myObserverXFrame()
{
this.register();
}
myObserverXFrame.prototype =
{
observe: function(aSubject, aTopic, aData)
{
var channel = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
//console.log("observing");
try
{ // getResponseHeader will throw if the header isn't set
hasXFO = channel.getResponseHeader('X-Frame-Options');
if (hasXFO)
{
// Header found, disable it
channel.setResponseHeader('X-Frame-Options', '', false);
}
}
catch (e) {}
}
},
register: function()
{
var observerService = Components.classes["#mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
observerService.addObserver(this, "http-on-examine-response", false);
observerService.addObserver(this, "http-on-examine-cached-response", false);
},
unregister: function()
{
}
}
var observer = new CommandLineObserver();
//addEventListener("unload", observer.unregister, false);
Thanks.
Related
I try to set up plugin ckeditor/ckeditor5-export-pdf on my Laravel App But I cant do this. I still get issues like: Uncaught TypeError: Failed to resolve module specifier "#ckeditor/ckeditor5-export-pdf/src/exportpdf". Relative references must start with either "/", "./", or "../".
I did all steps as in docs: https://ckeditor.com/docs/ckeditor5/latest/features/export-pdf.html#configuration But when I try use import ExportPdf from '#ckeditor/ckeditor5-export-pdf/src/exportpdf'; I get the error like above. Please help. Maybe some have stuck on this issue before
import ExportPdf from '#ckeditor/ckeditor5-export-pdf/src/exportpdf';
console.log(ExportPdf);
$(document).ready(function () {
/*function ExportPdf(editor) {
editor.execute('exportPdf');
}*/
function SimpleUploadAdapter(editor) {
editor.plugins.get('FileRepository').createUploadAdapter = function(loader) {
return {
upload: function() {
return loader.file
.then(function (file) {
return new Promise(function(resolve, reject) {
// Init request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/admin/instructions/ckmedia', true);
xhr.setRequestHeader('x-csrf-token', window._token);
xhr.setRequestHeader('Accept', 'application/json');
xhr.responseType = 'json';
// Init listeners
var genericErrorText = `Couldn't upload file: ${ file.name }.`;
xhr.addEventListener('error', function() { reject(genericErrorText) });
xhr.addEventListener('abort', function() { reject() });
xhr.addEventListener('load', function() {
var response = xhr.response;
if (!response || xhr.status !== 201) {
return reject(response && response.message ? `${genericErrorText}\n${xhr.status} ${response.message}` : `${genericErrorText}\n ${xhr.status} ${xhr.statusText}`);
}
$('form').append('<input type="hidden" name="ck-media[]" value="' + response.id + '">');
resolve({ default: response.url });
});
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
loader.uploadTotal = e.total;
loader.uploaded = e.loaded;
}
});
}
// Send request
var data = new FormData();
data.append('upload', file);
data.append('crud_id', {{ $instruction->id ?? 0 }});
xhr.send(data);
});
})
}
};
}
}
var allEditors = document.querySelectorAll('.ckeditor');
for (var i = 0; i < allEditors.length; ++i) {
ClassicEditor.create(
allEditors[i], {
extraPlugins: [SimpleUploadAdapter, /*ExportPdf*/],
/*toolbar: [
'exportPdf', '|',
],
exportPdf: {
stylesheets: [
'./path/to/fonts.css',
'EDITOR_STYLES',
'./path/to/style.css'
],
fileName: 'my-file.pdf',
converterOptions: {
format: 'A4',
margin_top: '20mm',
margin_bottom: '20mm',
margin_right: '12mm',
margin_left: '12mm',
page_orientation: 'portrait'
}
}*/
}
);
}
});
</script>```
I solved my problem with https://ckeditor.com/ckeditor-5/online-builder/ Builded what I want and setup it on my App
I use https://www.npmjs.com/package/ws npm package to communicate between my npm module and my chrome extension.
Connection is getting opened, but closes in few seconds.
I researched the topic and I found that I should send messages back and forth between webSocket server and Client to keep it alive.
I am sanding this messages every 2 sec but my connection is still closing.
Interesting stuff is that close event fires on node module side only, while chrome plugin does not fire the event. Here is a code from my chrome extension:
function myPlugin() {
myPlugin.prototype.socket = false;
myPlugin.prototype.isConnected = false;
myPlugin.prototype.port = false;
myPlugin.prototype.pluginName = "Tab Reloader";
myPlugin.prototype.init();
};
myPlugin.prototype = {
initListeners: function () {
chrome.browserAction.onClicked.addListener(function(tab) {
if (!this.isConnected) {
this.connectToServer();
} else {
this.disconnectFromServer();
}
}.bind(this));
},
setPort: function () {
chrome.storage.sync.get(['port'], function(items) {
this.port = items.port || '8001';
}.bind(this));
},
getTabsToReload: function (callback) {
var tabsToReload = [];
chrome.storage.sync.get(['hostName'], function(items) {
if (!items.hostName) {
chrome.tabs.query({active: true}, function(tabs) {
tabs.forEach(function (tab) {
tabsToReload.push(tab);
});
callback(tabsToReload);
});
} else {
chrome.tabs.query({}, function(tabs) {
tabs.forEach(function (tab) {
if (tab.url.indexOf(items.hostName) != -1) {
tabsToReload.push(tab);
}
});
callback(tabsToReload);
});
}
}.bind(this));
},
initSocketListeners: function () {
var fileExtIndex,
fileExt,
file;
this.socket.onmessage = function (ev) {
file = ev.data.toString();
fileExtIndex = file.lastIndexOf('.') + 1;
fileExt = file.slice(fileExtIndex),
fileNameStandardize = file.replace(/\\/g, '\/'),
indexOfLastSeparator = fileNameStandardize.lastIndexOf('/') + 1,
fileName = file.slice(indexOfLastSeparator);
if (file != 'pong' && file.indexOf('connected to server!!!') == -1) {
//do stuff
} else {
if (file == 'pong') {
this.isAlive = true;
}
}
}.bind(this);
this.socket.addEventListener('close', function (ev) {
console.log('connection Closed')
clearInterval(this.aliveInterval);
chrome.browserAction.setIcon({
path: {
"16": "img/icon_disabled_16.png",
"24": "img/icon_disabled_24.png",
"32": "img/icon_disabled_32.png"
}
});
this.isConnected = false;
}.bind(this));
},
connectToServer: function () {
this.socket = new WebSocket("ws://localhost:" + this.port);
this.socket.addEventListener('error', function (ev) {
this.isConnected = false;
alert('Error connecting to websocket server, make sure it\'s running and port ' + this.port + ' is not occupied by other process');
}.bind(this));
this.socket.addEventListener('open', function (ev) {
this.isConnected = true;
this.socket.send(this.pluginName + ' connected to server!!!');
this.initSocketListeners();
this.stayConnected();
this.isAlive = true;
this.aliveInterval = setInterval(function () {
this.checkIfAlive();
}.bind(this), 2500);
this.getTabsToReload(function (tabsToReload) {
tabsToReload.forEach(function (tab) {
chrome.tabs.update(tab.id, {url: tab.url});
});
});
chrome.browserAction.setIcon({
path: {
"16": "img/icon_active_16.png",
"24": "img/icon_active_24.png",
"32": "img/icon_active_32.png"
}
});
}.bind(this));
},
disconnectFromServer: function () {
this.socket.close();
},
stayConnected: function () {
setTimeout(function () {
this.socket.send('ping');
if (this.isConnected) {
this.stayConnected();
}
}.bind(this), 1000);
},
checkIfAlive: function () {
this.isAlive = false;
setTimeout(function () {
console.log(this.isAlive)
if (!this.isAlive) {
console.log(this.isAlive)
this.disconnectFromServer();
}
}.bind(this), 2000);
},
init: function () {
this.setPort();
this.initListeners();
}
}
window.onload = new myPlugin();
And here is my node module code:
"use strict";
//var WebSocketServer = require('websocketserver');
//var WebSocketServer = require("nodejs-websocket")
var WebSocket = require('ws');
class MyModule {
constructor(options) {
this.options = options;
this.server = false;
this.pluginName = 'Some';
this.isConnected = false;
this.connection = false;
this.init();
return this.refreshTab.bind(this);
}
init() {
var port = this.options ? this.options.port : false;
this.server = new WebSocket.Server({port: port || 8001});
this.server.on('connection', (websocket) => {
console.log('Connection open');
this.websocket = websocket;
this.isConnected= true;
this.initListeners();
});
}
refreshTab(uploadedFiles) {
if (this.isConnected) {
if (Array.isArray(uploadedFiles)) {
uploadedFiles.forEach(function (el) {
this.websocket.send(el.toString());
}.bind(this));
} else {
this.websocket.send(uploadedFiles ? uploadedFiles.toString() : 'reload');
}
} else {
console.log('You are not connected to server yet.');
}
}
initListeners() {
this.websocket.on('message', (message) => {
if (message == 'ping') {
this.websocket.send('pong');
}
});
this.websocket.on('close', () => {
this.isConnected = false;
console.log(this.pluginName + ' connection is closed');
});
}
};
module.exports = MyModule;
Appreciate any help,
Thanks in advance.
So my problem was actually in manifest.json
"background": {
"scripts": ["js/tab_reloader.js"],
"persistent": false
}
"persistent" was set to false, it transformed my Background page into Event Page. And event page is unloaded from memory after a period of time, which was killing the connection. After I set "persistent" to true the problem got fixed.
My code is as below
var originalTitle = document.title.split("#")[0];
var testtar = document.getElementsByTagName('title')[0];
try{
document.attachEvent('onpropertychange', function (evt) {
console.log('inside attachEvent');
if(evt.propertyName === 'title' && document.title !== originalTitle) {
setTimeout(function () {
document.title = originalTitle;
}, 0);
}
});
}
catch(e){
function disconnect(){
observer.disconnect();
setTimeout(function(){
observer.observe(testtar, config);
console.log(observer)
},1000);
}
var observer = new MutationObserver(function(mutations) {
testtar.innerHTML = originalTitle;
disconnect();
});
var config = { attributes: true, childList: true, characterData: true, characterDataOldValue: true };
observer.observe(testtar, config);
};
I am trying to check for title change using MutationObserver. but once i call observer.disconnect() and again call its observe() method it doesn't work.
the title changes for the second time but still testtar.innerHTML is not set to originalTitle. please help
As I want to implement a chat in AngularJS, I want to use the promise/deferred principle. My ChatService looks like the following:
factory('ChatService', ['$q', '$resource', function($q, $resource) {
var Service = {};
var connected = false;
var connection;
var chatResource = $resource('/guitars/chat/:action', {action: '#action'}, {
requestChatroomId: {
params: {
action: 'requestChatroomId'
},
method: 'GET'
},
sendMessage: {
params: {
action: 'sendMessage'
},
method: 'POST'
}
});
Service.connect = function(cb) {
var deferred = $q.defer();
chatResource.requestChatroomId(function(data) {
connection = new WebSocket('ws://127.0.0.1:8888/realtime/' + data.chatroomId);
connection.onerror = function (error) {
deferred.reject('Error: ' + error);
};
connection.onmessage = function (e) {
cb.call(this, e.data);
deferred.notify(e.data);
};
connected = true;
});
return deferred.promise;
};
Service.sendMessage = function(msg) {
if(!connected) {
return;
}
chatResource.sendMessage({message: msg});
}
return Service;
}])
My controller using the ChatService is:
app.controller('ChatCtrl', ['$scope', 'ChatService', function($scope, ChatService) {
$scope.chat = {};
$scope.chat.conversation = [];
var $messages = ChatService.connect(function(message) {
$scope.$apply(function() {
// #1 THIS FIRES EVERY TIME
$scope.chat.conversation.push(message);
});
});
$messages.then(function(message) {
console.log('Finishes - should never occur!')
}, function(error) {
console.log('An error occurred!')
}, function(message) {
// #2 THIS FIRES ONLY IF THERE IS AN INTERACTION WITH THE ANGULAR MODEL
console.log(message);
});
$scope.sendMessage = function(event) {
ChatService.sendMessage($scope.chat.message);
$scope.chat.message = '';
};
}]);
If something is pushed from the server, callback #1 is called, but callback #2 wont be called until there is some interaction with the angular-model, i.e. start writing something in the input-Box. What is the reason for that behaviour?
Okay the reason was, that AngularJS was not aware of a change. So I injected the $rootScope to my ChatService:
factory('ChatService', ['$q', '$resource', '$rootScope', function($q, $resource, $rootScope) {
and in connection.onmessage I called $apply() on $rootScope:
connection.onmessage = function (e) {
deferred.notify(e.data);
$rootScope.$apply();
};
Is it possible adapt this code for crossdomain and how
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() { alertContents(http_request); };
http_request.open('GET', url, true);
http_request.send(null);
}
function alertContents(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
receiveData(http_request.responseText);
} else {
alert("Îòâåò ñåðâåðà ïîëó÷åí, íî åñòü îøèáêà");
}
}
}
The same origin policy prevents JavaScript reading data from different origins under normal circumstances.
You can work around with:
A proxy for the data on the page's origin
JSONP
CORS (limited browser support, but possibly good enough for prime time now)