Chrome Extensions and loading external Google APIs Uncaught ReferenceError - api

Right now I'm in the process of creating a Chrome extension. For it, I need to use Google's Calendar Data API. Here is my manifest.json file:
{
"name": "Test",
"version": "1.0",
"background_page": "background.html",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["jquery.js", "content_script.js"]
}
],
"permissions": [
"tabs", "http://*/*"
]
}
I've tried adding the following to the js part of the manifest file but that throws an error when loading the extension.
http://www.google.com/jsapi?key=keyhere
I've also tried adding
document.write('<script type="text/javascript" src="http://www.google.com/jsapi?key=keyhere"></script>');
to my background.html file. However, whenever I call
google.load("gdata", "1");
I get an error that says Uncaught ReferenceError: google is not defined. Why is my extension not loading this api when it loads the other ones fine?

You can't include external script into content_scripts.
If you want to inject <script> tag using document.write then you need to mask slash in a closing tag:
document.write('...<\/script>');
You can include your external api js into background page just as usual though:
<script type="text/javascript" src="http://www.google.com/jsapi?key=keyhere"></script>
If you need this api in content scripts then you can send a request to your background page and ask it to do API-dependent stuff there, and then send a result back to your content script.

Thanks for that link, it helped a lot. However, now I've run into another interesting problem.
for (var i = rangeArray.length - 1; i >= 0; i--) {
var myLink = document.createElement('a');
myLink.setAttribute('onclick','helloThere();');
myLink.innerText ="GO";
rangeArray[i].insertNode(myLink);
}
Now I get the error, "helloThere is not defined" even though I placed that function about ten lines above the current function that has the above loop in the same file. Why might this be happening? And if I do:
for (var i = rangeArray.length - 1; i >= 0; i--) {
var myLink = document.createElement('a');
myLink.setAttribute('onclick','chrome.extension.sendRequest({greeting: "hello"}, function(response) { });');
myLink.innerText ="GO";
rangeArray[i].insertNode(myLink);
}
I get Uncaught TypeError: Cannot call method 'sendRequest' of undefined

This is because there is some syntax error in your code. I had same problem. I opened my background.html page in fire fox with fire-bug plug-in enabled. Fire-bug console should me the error, I fixed and it is working now.

Related

Cypress - run test in iframe

I'm trying to find elements in iframe but it doesn't work.
Is there anyone who have some system to run tests with Cypress in iframe? Some way to get in iframe and work in there.
It's a known issue mentioned here. You can create your own custom cypress command which mocks the iframe feature. Add following function to your cypress/support/commands.js
Cypress.Commands.add('iframe', { prevSubject: 'element' }, ($iframe, selector) => {
Cypress.log({
name: 'iframe',
consoleProps() {
return {
iframe: $iframe,
};
},
});
return new Cypress.Promise(resolve => {
resolve($iframe.contents().find(selector));
});
});
Then you can use it like this:
cy.get('#iframe-id')
.iframe('body #elementToFind')
.should('exist')
Also, because of CORS/same-origin policy reasons, you might have to set chromeWebSecurity to false in cypress.json (Setting chromeWebSecurity to false allows you to access cross-origin iframes that are embedded in your application and also navigate to any superdomain without cross-origin errors).
This is a workaround though, it worked for me locally but not during CI runs.
This works for me locally and via CI. Credit: Gleb Bahmutov iframes blog post
export const getIframeBody = (locator) => {
// get the iframe > document > body
// and retry until the body element is not empty
return cy
.get(locator)
.its('0.contentDocument.body').should('not.be.empty')
// wraps "body" DOM element to allow
// chaining more Cypress commands, like ".find(...)"
// https://on.cypress.io/wrap
.then(cy.wrap)
}
spec file:
let iframeStripe = 'iframe[name="stripe_checkout_app"]'
getIframeBody(iframeStripe).find('button[type="submit"] .Button-content > span').should('have.text', `Buy me`)
that is correct. Cypress doesn't support Iframes. It is simple not possible at the moment. You can follow (and upvote) this ticket: https://github.com/cypress-io/cypress/issues/136

requirejs loading file from different path

I've a webpage , where I've included the requirejs via script tag like -
<script data-main="/media/course-book-app/courses.require.main.js" src="/media/common/vendor/requirejs/require.js"></script>
On Safari browser, I'm getting error like -
What is causing this issue?
This issue is very frequent on Safari but on chrome it is less frequent.
Testing URL
From https://requirejs.org/docs/errors.html#scripterror (which is linked right there in the error). Follow the instructions and look at the script that caused the error
This occurs when the script.onerror function is triggered in a
browser. This usually means there is a JavaScript syntax error or
other execution problem running the script. To fix it, examine the
script that generated the error in a script debugger.
This error may not show up in IE, just other browsers, and instead, in
IE you may see the No define call for ... error when you see "Script
error". This is due to IE's quirks in detecting script errors.
Here is the way to use requirejs correctly. This ensures the configuration gets loaded before loading any module -
define('requireconfig', function(){
require.config({
paths: {
"jquery": "/common/vendor/jquery/jquery-1.9.1.min",
"backbone": "/common/vendor/backbone/backbone.min-1.1.2",
"underscore": mediaPath + "/common/vendor/underscore/underscore.min-1.7.0"
},
shim: {
backbone : {
deps: ["jquery","underscore"],
exports: "Backbone"
},
}
});
});
define('main', ['requireconfig'], function () {
'use strict';
});
// loading main module which loads the requirejs configuration
requirejs(['main'],()=>{
requirejs(['jquery'], ($)=>{//jquery loaded});
}, ()=>{//error loading module})

ArcGIS Api (Esri) triggering multipleDefine error

I have this weird issue while using ArcGIS API for JavaScript v4.4 in my code. I am trying to build an Excel Web Add-in in which I would like to load an ArcGIS map but when I load ArcGIS I get a multipleDefine error.
ArcGIS is getting bundled with Dojo which is used as the loader for all the ArcGIS/esri packages. I have no other choices to load my own custom JS bundles with Dojo because of the way ArcGIS has built their API. So I can't decide to not use Dojo and thus not getting the multipleDefine error.
I load my own JS files like this:
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>
<script>
var dojoConfig = {
parseOnLoad: false,
async: false,
// we make aliases for our js file
aliases:  [
['index',  './Bundles/index.js'],
],
};
</script>
<script src="https://js.arcgis.com/4.4/init.js"></script>
<script>
require(['index'], function (index) {
//...do something
});
</script>
When I restart the page I get a multipleDefine error once in every two/three trials. After a lot of investigation I understood that the error lies with the Office.js API but I had a hard time to find a good solution.
After a while I found the cause of the problem; we cannot start office-js and Dojo together because they both want to add scripts in the head tag of our page and somehow they end up in conflict with one another, thus we get the dreaded multipleDefined Dojo error and some of our files do not get loaded.
Once this cause was identified I decided to solve it by making sure Dojo, Argis and my custom js files got loaded once Office and dependencies were fully loaded.
I implemented it like this in my js code:
// This Dojo config variable has to be defined before Dojo is loaded in our scripts
var dojoConfig = {
// we make aliases for our custom js file
aliases: [
['index', './Bundles/index.js'],
],
// We require our dependencies (our own code bundles) with Dojo.
// Notice that it is mandatory to bundle our js files
// as AMD Modules for Dojo to be able to load them as dependencies.
deps: ['index'],
};
// Once office has fully initialized we can add our arcgis file and let
// him load our own required javascript files.
// We cannot start Office-js and Dojo/Arcgis together because they both
// want to add scripts in the head tag of the HTML page and
// somehow they end up in conflict, thus we get the dreaded
// multipleDefined Dojo error and some of our files
// do not get loaded.
Office.initialize = function (reason) {
// we manually add the Arcgis script to the header of our page
// once we are sure Office and dependencies has fully loaded.
var tag = document.createElement('script');
tag.src = 'https://js.arcgis.com/4.4/init.js';
document.getElementsByTagName('head')[0].appendChild(tag);
};
Once this was added the code started working like a charm.

Dojo - Issue loading widget cross-domain

I'm working on a project that requires that some custom Dojo widgets (i.e., widgets we have written ourselves) are loaded from another server. Despite my best efforts over several days, I cannot seem to get Dojo to load the widgets.
Dojo is loaded from the Google CDN, the widget is loaded from www.example.com, and the website is located at www.foo.com.
I cannot post the actual project files (this is a project for a company), but I have reproduced the error with smaller test files.
Test.html (on www.foo.com):
<html>
<div id="content"></div>
<script>
var djConfig = {
isDebug: true,
modulePaths: {
'com.example': 'http://example.com/some/path/com.example'
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.4.3/dojo/dojo.xd.js.uncompressed.js"></script>
<script type="text/javascript">
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.addOnLoad(function() {
dojo.require("com.example.widget.Test", false);
dojo.addOnLoad(function() {
new com.example.widget.Test().placeAt(dojo.byId('content'));
});
});
</script>
</html>
Test.xd.js (at www.example.com/some/path/com.example/widget/Test.xd.js):
dojo.provide("com.example.widget.Test");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.declare("com.example.widget.Test", [dijit._Widget, dijit._Templated], {
templateString: "<div dojoAttachPoint=\"div\">This is a test</div>",
postCreate: function() {
console.log("In postCreate");
console.log(this.div);
this.div.innerHTML += '!!!';
}
});
In Firebug, I am seeing an error after a delay of a few seconds saying that the cross-domain resource com.example.widget.Test cannot be loaded. However, in the 'Net' tab I am able to see that Test.xd.js is successfully downloaded, and I am able to set a breakpoint and see that the dojo.declare executes and completes without error.
I appreciate any help. Please let me know if there is any other information I can provide.
There is a different way for handling the module declarations in XD-loader. This is due to how the loader handles 'module-ready' event. You will most likely experience, that the dojo.addOnLoad never runs, since it 'knows' that certainly - some required modules are not declared.
Even so, they may very well be declared - and the change in 1.7+ versions of dojotoolkit seem to reckognize that fact. The reason for this, i believe, is that the mechanism for 'module-ready' is not implemented correctly in your myModule.xd.js modules.
It is basically a 'header' or 'closure' of the declaration, involving a few steps - wrapping everything in your basic module from dojo.provide and eof
Standard example boiler module file '{{modulePath}}/my/Tree.js'
dojo.provide("my.Tree");
dojo.require("dijit.Tree");
dojo.declare("my.Tree", dijit.Tree, {
// class definition
});
X-Domain example boiler module file '{{modulePath}}/my/Tree.xd.js
dojo._xdResourceLoaded(function(){
return {
depends: [
["provide", "my.Tree"],
["require", "dijit.Tree"]
],
defineResource: function(dojo) {
///////////////////////////////
/// Begin standard declaration
dojo.provide("my.Tree");
dojo.require("dijit.Tree");
dojo.declare("my.Tree", dijit.Tree, {
// class definition
});
/// End standard declaration
///////////////////////////////
}
}
})();

MonoRail - How to write JavaScript within .vm page

I'm using MonoRail and tried to write a tag within a .vm view to write some JavaScript:
<script type="text/javascript">
//<![CDATA[
$j(document).ready(function()
{
$j('#business_parentbusinesstype_id').change(function()
{
$j.ajax({
url:'http://localhost:88/admin/business/GetChildBusinessTypes',
data: { parentId: $j('#business_parentbusinesstype_id').val() },
dataType: 'script'
});
});
});
//]]>
</script>
You would think that this would work since it's an HTML page but it gives me this error:
Unable to process resource 'admin\business\new.vm': Encountered "\r\n url:\'http://localhost:88/admin/business/GetChildBusinessTypes\',\r\n data: { parentId: " at line 7, column 12.
Was expecting:
...
What am I missing?
I'm wondering if nVelocity is seeing the "$j" and trying to find it in the property bag and execute the "ajax" method. If the "$j" is the short-hand for jQuery, try changing it to the full "jQuery" and see if that works.
Monorail uses the $ sign for objects in the Property Bag. Some things you can do is you can either use the longhand(jQuery.someFuntion()), or move the js to its own js file that you then just include in your vm file.