I have a simple page that is being served by AngulraJs application. The page has div with a value of Test.
<div id="test">Test</div>
My goal is to read this value from localhost. Basically, I am writing a plugin for an application. This application is a desktop app that has its own web server built in and plugins are written in javascript. My goal is to read the test value. The problem that I am facing though is that I get prevented by CORS.
From everything I have read (and I have been reading a lot), I need to add the Access-Control-Allow-Origin header in order for this to work. What my problem is how do I add a header with angular js for one page only.
I have found the follow SO answer: Set HTTP header for one request
I have also read a lot of documentation such as this: https://docs.angularjs.org/api/ng/service/$http
However, I am still confused with is one thing:
The url that is entered, what should it be in my case? Consider the following example, how would you write it to work for my case if the Angularjs app is sitting on www.somedomain.com and it is being called by javascript code from my localhost machine.
$http.get('what url goes here?', {
headers: {'Access-Control-Allow-Origin': '*'}
});
I also have a small sub question, with the above example, will I be overriding any of the existing headers or will it only append a new header?
EDIT:
Angularjs code serving back the page:
(function() {
'use strict';
angular
.module('App')
.controller('Test', Test);
function Test($scope, $http) {
var T = this;
T.test = test;
function test(){
return "Test";
}
}
})();
HTML
<div id="test">{{T.test()}}</div>
The header Access-Control-Allow-Origin must be set on returned header, not request header.
So config your server to return the page 'what url goes here?' to have that header return.
If you have no control over 'what url goes here?' then you have to write a proxy with your web server: webserver get that page content then return to your script.
Related
I have some 3rd parties JavaScript files in my code which includes some another JavaScript files which are loaded after some event. I don`t have control to change code inside 3rd party JavaScript file.
My website is hosted on https and included files are loading over http since browser does not allow this to load and says "mix content blocked".
Can I write interceptor that will intercept this call and will change http to https.
When you are including a 3rd party library in your code, the loading browser will make the request to the server where the code is hosted. You can download the code, if it's available and there is no legal issues to do so, and host it on your server. You have to understand that not all data needs to go through https (to increase performance for example).
Take a look at this link to have a better understanding of the issue and how the prevent it.
Thanks for your comments but I don`t believe I should change 3rd party libraries as there might be some legal issues with it.
But I found something which can solve my issue by intercepting all the http calls and forward it to https by adding following code in your JavaScript at global.
Object.defineProperty(HTMLScriptElement.prototype, 'src', {
get: function() {
return this.getAttribute('src')
},
set: function(url) {
var prefix = "http://";
if (url.startsWith(prefix))
url = "https://" + url.substr(prefix.length);
console.log('being set: ' + url);
this.setAttribute('src', url);
}
});
Originally posted here : Force JavaScript to load additional resources over https
I'm trying to familiarize myself with the concept of using script tags. I'm making a ruby on rails app that does something as simple as alert "Hi" when a customer visits a page. I am testing this public app on a local server and I have the shopify_app gem installed. The app has been authenticated and I have access to the store's data. I've viewed the Shopify API documentation on using script tags and I've looked at the Shopify Embedded App example that Shopify has on GitHub. The documentation details the properties of a script tag and gives examples of script tags with their properties defined, but doesn't say anything about where to place the script tag in an application, or how to configure an environment so that the js file in the script tag will go through.
I've discovered that a js file being added with a script tag will only work if the js file is hosted online, so I've uploaded the js file to google drive. I have the code for the script tag in the index action of my HomeController (the default page for the app). This is the code I'm using:
def index
if response = request.env['omniauth.auth']
sess = ShopifyAPI::Session.new(params[:shop], response[:credentials][:token])
session[:shopify] = sess
ShopifyAPI::Base.activate_session(sess)
ShopifyAPI::ScriptTag.create(
:event => "onload",
:src => "https://drive.google.com/..."
)
end
I think the problem may be tied to the request.env. The response is not being read as request.env[omniauth.auth] and I believe that the response coming back as valid may be required for the script tag to go through.
The method that I tried above is from the 2nd answer given in this topic: How to develop rails app for shopify with ScriptTags.
The first answer suggested using this code:
ShopifyAPI::Base.site = token
s = ShopifyAPI::ScriptTag.create(:events => "onload",:src => "your javascript url")
However, it doesn't say where to place both lines of code in a rails application. I tried putting the second line in a js file in my rails application, but it did not work.
I don't know if I'm encountering problems because I'm running the app on a local server or if there is something missing from the configuration of my application.
I'd appreciate it if anyone could point me in the right direction.
Try putting something like this in config/initializers/shopify_app.rb
ShopifyApp.configure do |config|
config.api_key = "xxx-xxxx-xxx-xxx"
config.secret = "xxx-xxxx-xxx-xxx"
config.scope = "read_orders, read_products"
config.embedded_app = true
config.scripttags = [
{event:'onload', src: 'https://yourdomain.herokuapp.com/javascripts/yourjs.js'}
]
end
Yes, you are correct that you'll need the js file you want to include for your script tag publicly available - if you are using localhost for development look into ngrok.
Do yourself the favor of ensuring your callbacks use SSL when interacting with the Shopify API (i.e. configure your app with https://localhost/ as a callback setting in the Shopify app settings). I went through the trouble of configuring thin as the web server locally with a self-signed SSL certificate.
With a proper set up you should be able to debug why the response is failing the omniauth check.
I'm new to the Shopify API(s), but not Rails. Their documentation leaves a lot to be desired.
Good luck to you sir,
I am using UI-Router for routes/states in my app and URLs were having "#" so to remove this , I used $locationProvider like -
function configState($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
Added ngRoute in module dependency and added <base href="/" > in my index.html.
Problem -
If I am using it as a normal app like in same tab and navigates to other state, it works BUT whenever I pasted the URL in another tab and hit enter its throwing Cannot GET /app_views/contacts URL is like - http://localhost:9000/app_views/contacts
Though with hash in URL it works in both way manner.
You are likely getting this error because your server is not configured correctly. In other words when you manually enter /app_views/contacts it will make a request to the server for that page. For this to work properly you need configure your server to route all traffic to your index.html page in order for Angular to properly take over and display the correct view.
Here is a related post Reloading the page gives wrong GET request with AngularJS HTML5 mode
I just got started with firefox addons to help my team fasten up our work, what i am trying to create:
When being on a specific site (let's call it mysite.com/input) i want to fill out automatically an input with an id: "textinput" from the value that is stored on the clipboard.
Yeah it is simple yet it would be simply enough to paste it, wouldn't it?... now here is the twist:
I need an other form of the value: on the clipboard it is x/y/z. There is a database site (let's call it database.com) on which searching like database.com?s=x/y/z would directly give the page from where it is possible to gain the correct value as it has an id: #result
I got lost how to properly communicate between page and content scripts, i'm not even sure in what order should i use the pagemod and the page-worker
Please help me out! Thank you!
The basic flow is this:
In your content script, you get the value form the form, somehow. I'll leave that up to you.
Still in the content script, you send the data to main.js using self.port.emit:
Code:
self.port.emit('got-my-value', myValue);
In main.js, you would then receive the 'got-my-value' event and make a cross-domain request using the request module.
Code:
require('page-mod').PageMod({
include: 'somesite.com',
contentScriptFile: data.url('somescript.js'),
onAttach: function(worker) {
worker.port.on('got-my-value', function(value) {
require('request').Request({
url: 'http://someurl.com',
onComplete: function(response) {
console.log(response);
// maybe send data back to worker?
worker.port.emit('got-other-data', response.json);
}
}).post();
});
}
});
If you need to receive the data back in the original worker, you would another listener for the event coming back.
Code:
self.port.on('got-other-data', function(value) {
// do something
})
I've been struggling with the same issue for the past 2 days until I found this:
https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts/Cross_Domain_Content_Scripts
They indicate the following:
However, you can enable these features for specific domains by adding
them to your add-on's package.json under the "cross-domain-content"
key, which itself lives under the "permissions" key:
"permissions": {
"cross-domain-content": ["http://example.org/", "http://example.com/"] }
The domains listed must include the scheme
and fully qualified domain name, and these must exactly match the
domains serving the content - so in the example above, the content
script will not be allowed to access content served from
https://example.com/. Wildcards are not allowed. This feature is
currently only available for content scripts, not for page scripts
included in HTML files shipped with your add-on.
That did the trick for me.
Hey everyone, I'm working on a widget for Apple's Dashboard and I've run into a problem while trying to get data from my server using jquery's ajax function. Here's my javascript code:
$.getJSON("http://example.com/getData.php?act=data",function(json) {
$("#devMessage").html(json.message)
if(json.version != version) {
$("#latestVersion").css("color","red")
}
$("#latestVersion").html(json.version)
})
And the server responds with this json:
{"message":"Hello World","version":"1.0"}
For some reason though, when I run this the fields on the widget don't change. From debugging, I've learned that the widget doesn't even make the request to the server, so it makes me think that Apple has some kind of external URL block in place. I know this can't be true though, because many widgets phone home to check for updates.
Does anyone have any ideas as to what could be wrong?
EDIT: Also, this code works perfectly fine in Safari.
As requested by Luca, here's the PHP and Javascript code that's running right now:
PHP:
echo $_GET["callback"].'({"message":"Hello World","version":"1.0"});';
Javascript:
function showBack(event)
{
var front = document.getElementById("front");
var back = document.getElementById("back");
if (window.widget) {
widget.prepareForTransition("ToBack");
}
front.style.display = "none";
back.style.display = "block";
stopTime();
if (window.widget) {
setTimeout('widget.performTransition();', 0);
}
$.getJSON('http://nakedsteve.com/data/the-button.php?callback=?',function(json) {
$("#devMessage").html(json.message)
if(json.version != version) {
$("#latestVersion").css("color","red")
}
$("#latestVersion").html(json.version)
})
}
In Dashcode click Widget Attributes then Allow Network Access make sure that option is checked. I've built something that simply refused to work, and this was the solution.
Cross-domain Ajax requests ( Using the XMLHttpRequest / ActiveX object ) are not allowed in the current standard, as per the W3C spec:
This specification does not include
the following features which are being
considered for a future version of
this specification:
Cross-site XMLHttpRequest;
However there's 1 technique of doing ajax requests cross-domain, JSONP, by including a script tag on the page, and with a little server configuration.
jQuery supports this, but instead of responding on your server with this
{"message":"Hello World","version":"1.0"}
you'll want to respond with this:
myCallback({"message":"Hello World","version":"1.0"});
myCallback must be the value in the "callback" parameter you passed in the $.getJSON() function. So if I was using PHP, this would work:
echo $_GET["callback"].'({"message":"Hello World","version":"1.0"});';
Apple has some kind of external URL block in place.
In your Info.plist you need to have the key AllowNetworkAccess set to true.
<key>allowNetworkAccess</key>
<true/>
Your code works in Safari because it is not constrained in the dashboard sever and it is not standards complient in that it DOES allow cross site AJAX. FF IS standards complient in that it DOES NOT allow cross site ajax.
If you are creating a dashboard widget, why don't you use the XMLHttpRequest Setup function in the code library of DashCode. Apple built these in so you don't need to install 3rd party JS libraries. I'm not sure about JSON support but perhaps starting here will lead you in a better direction.
So another solution is to create your own server side web service where you can control the CORS of, the users web browser can't access another site, but if you wrap that other site in your own web service (on the same domain) then it does not cause an issue.
Interesting that it works in Safari. As far as I know to do x-domain ajax requests you need to use the jsonp dataType.
http://docs.jquery.com/Ajax/jQuery.getJSON
http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/
Basically you need to add callback=? to your query string and jquery will automatically replace it with the correct method eg:
$.getJSON("http://example.com/getData.php?act=data&callback=?",function(){ ... });
EDIT: put the callback=? bit at the end of the query string just to be safe.