google-chrome-extension,requirejs,typescript , Mismatched anonymous define() in Chrome extension content script

Mismatched anonymous define() in Chrome extension content script


Tag: google-chrome-extension,requirejs,typescript

I'm trying to build a Chrome extension with TypeScript.
The setup is quite simple:

In manifest.json

    "permissions": [

    "content_scripts": [
        "matches": [ "http://*/*", "https://*/*" ],
        "js": [ "scripts/require.js", "scripts/require-cs.js",
                "scripts/main.js", "scripts/contentscript.js" ],
        "run_at": "document_end",
        "all_frames": true

In model.ts:

export class WebPage
    private id: number;
    private processed: boolean;

    get Id() { return; }
    set Id(value: number) { = value };

    get Processed() { return this.processed; }
    set Processed(value: boolean) { this.processed = value };

    constructor(id: number)
    { = id;
        this.processed = false;

When compiled the resulting JavaScript starts with:

define(["require", "exports"], function (require, exports) {
    var WebPage = (function () 
           //Code omitted to keep the SO question short

In main.ts:

(function ()
    console.log("Executing main.js");

            baseUrl: "scripts", paths: { "model" : "model" }

In contentscript.ts:

import model = require("model");

console.log("Processing page");
var page = new model.WebPage(1);
page.Processed = true;
console.log("Done processing page");

When compiled the resulting JavaScript looks like this:

define(["require", "exports", "model"], function (require, exports, model) {
    console.log("Processing page");
    var page = new model.WebPage(1);
    page.Processed = true;
    console.log("Done processing page");

And finally in require-cs.js:

console.log("Executing requirejs-cs.js");

require.load = function (context, moduleName, url) {

    console.log("require.load called");
    var xhr = new XMLHttpRequest();"GET", chrome.extension.getURL(url) + '?r=' + (new Date()).getTime(), true);

    xhr.onreadystatechange = function (e) {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log("evaluating" + url)

Which is what I found in all the other questions related to my issue.

All of this results in the following output when loading a page:

Uncaught Error: Mismatched anonymous define() module: function (require, exports, model) {
    console.log("Processing page");
    var page = new model.WebPage(1);
    page.Processed = true;
    console.log("Done processing page");

I've read those docs, I went through a lot of similar questions on SO,
but I haven't found anything that works for me yet.
Most questions deal with JavaScript specifically,
perhaps there is something missing on the TypeScript side of things?

Note: The TypeScript compiler is configured to use AMD.


The docs for the error message state:

Be sure to load all scripts that call define() via the RequireJS API. Do not manually code script tags in HTML to load scripts that have define() calls in them.

As described in this question, it seems that if you use import in a type script, it will be turned into a module when compiled using AMD. So by including "scripts/contentscript.js" as a content script you are trying to load a module script without using the RequireJS API. You can try removing contentscript.js from the content_scripts entry in the manifest and adding the following to main.js:

requirejs(["contentscript"], function() {});


r.js requireJS. Must I modify my HTML? [duplicate]

This question already has an answer here: Javascript requirejs in development but compiled in production 2 answers Using requireJS to load 4 JS files, my HTML markup looks like this : <script data-main="js/app" src="js/vendor/require.js"></script> I run r.js to compile files to main-built.js. How can I now ask requireJS to...

Can I fire up a Chrome extension API from code?

Is it possible to launch a Google Chrome extension within a website? E.g run some javascript that will launch the extensions UI? I'm building a web-app that will allow users to take screenshots of their desktop and edit them. I've got a sample extension up and running using dektopCapture but...

RequireJS local var not matching

Can anyone explain why this might be the case? I am in a RequireJS module that has zero dependencies. I am trying to create a singleton that represents the view state, to avoid a global variable. But for some reason the getter that is trying to retrieve a property from...

node.js continues execution without waiting for a require to complete.

I'm trying to access a variable in a required node file. However the file requiring it always continues without waiting for the variable to be set. How do I get to wait before continuing? I have two files: databaseUrl = 'mongodb://localhost/db' mongoose = require('mongoose') mongoose.connect(databaseUrl) db = mongoose.connection...

how can i use require(“”); in javascript

i want to use a plugin in Firefox that it is in this. in this plugin tutorial use require function, and it is: require("sdk/preferences/service"); but i get error that require is not defined. so i search and download requireJS. but when attach this i get error module name sdk/preference/service has...

Using Asynchronous Module load in javascript library project

I am working on an javascript project which will be provided as a third-library. And there are a lot of modules and templates which is a waste of time and performance if loading them all at once. So I think use a module loader like requirejs maybe a good idea....

IndexedDB: Can you manually initiate a version change transaction?

I am writing a chrome extension that utilizes IndexedDB to store some information client side in an IDBObjectStore within an IDBDatabase. The nature of the data is such that I need my users to be able to modify the object store at their whim. (add new objects modify existing ones...

$injector:modulerr even after defining module

With reference to this link : and source code shared at : I am creating a simple angular app, which has one abstract state too. and getting the following error : Uncaught Error: [$injector:modulerr]$injector/modulerr?p0=parentConnect&p1=E…8000%2Fparentconn%2Fbower_components%2Fangular%2Fangular.min.js%3A17%3A381) Folder Structure is : index.html <!DOCTYPE html>...

Meta tags in chrome extension manifest.json?

I'll give a contrived example: Imagine that I wanted to list my Chrome extension on the Chrome Web Store under the title "Brad's Animal Names Extension" but I also wanted my extension to be revealed in the search results for "elephant". Is there any way I can do this without...

Create custom mode of ace-editor without requireJS [closed]

I want to create an angular service module can generate custom mode of ace-editor. But for creating custom mode of ace-editor, it used requireJS. I don't want to use it in my angular service module. So I wonder how to create custom mode of ace-editor without requireJS?

Difference between bower, browserify, requirejs, webpack?

I'm used to simple and small JS projects where the JS dependencies are concatenated and minified as part of the build process using something like gulp and the script tag in the html contains the hardcoded path to that minified JS file. It's not elegant and probably has several disadvantages,...

What is the name of the language in which the main program of Chromium is written?

We would like to develop a new plugin for Chromium. To achieve this goal, we must learn at least one computer language. We do not know its / their name(s). Do you know the name of the computer language in which is written the program contains 1) the variable whose...

RequireJS with CommonJS modules

Using RequireJS with CommonJS modules, what happens when I do this: define(function(require, exports, module) { //Put traditional CommonJS module content here var simpleCommonJSModule = require('simple-commonjs-module'); module.exports = new String('foo'); return { //return empty object along with using module.exports } }); if I return something, I assume the module.exports will be...

Using openweathermap api for free

Can I use openweathermap api for free in a chrome extension? I am trying to build a chrome extension which will use openweather map api. Can I use it for free if I want to place it on webstore?

Host my own chrome extension in my website

I have developed one chrome extension and i want to use it on some windows pc's all over the world (of course the owners know me and my work) but i dont want to upload it on WEBSTORE since its only for something we use for ourselfs. Could i host...

Create a module with submodules

I have a small homebrewed framework. I'm using this in several projects and I would like to bring that in a handy format for reusing it. I would like to organize the code as follows: Each prototype has its own file Each file is a require.js module I would like...

How does an unpublished extension get weekly users?

This is weird. I have an extension that is not available through the webstore because it's marked as private and is still pending review. However, I see the weekly users count increasing. When the counter was at 1, I thought it was somehow tracking my own usage of the locally...

Run a function from injected js

I have been going around in circles with this, so I would appreciate some help This is what I want to achieve User presses my extension ison Popup appears with two buttons, 'run function a' and 'run function b' When they press a button it runs the function in my...

Looking for tool that prevent script to become unresponsive [on hold]

For a side project I need to generate a lot of data from a WebGL Application. This Web App is mostly a personal tool and I really don't care if my browser become unresponsive (I mean, I know it will). Does someone know a browser/tool/plugin that could allow me to...

Visual Studio 2015 RC + RequireJS + jQuery

I'm using Visual Studio 2015RC + Cordova CLI 5.1.1 + TypeScript + RequireJS + jQuery . I'd like to change the location of my jquery.js file from the scripts folder to scripts/lib. I added a requirejs.config and changed the jQuery location. requirejs.config({ baseUrl: 'scripts/lib', paths: { jquery: 'jquery' } });...

angular.js loaded instead of angular.min.js with requirejs

I'm using Webjars to import AngularJS into my web project. For some reason the minified version of AngularJS won't be served even though I'm referencing those in my main. I was expecting to see angular.min.js and angular-route.min.js being loaded, but I'm seeing the regular angular.js and angular-route.js. What am I...

How to make function in loop run synchronously?

Am working on a chrome plugin, and need to sendMessage from an 'app page' to a 'content script' and then get the return messages, from inside a loop. But since the loop doesn't wait for the sendMessage to return a value before starting on the next iteration, it is screwing...

Access DOM elements data document->Iframe ->Iframe->method chrome extension

I'm trying to access some data from an iframe nested within an iframe, from developers console: Object.keys(document.getElementById("contentBody"). contentDocument.getElementById('rawContent'). contentDocument.defaultView.window.messages) ["", "", "", "", "", ""] That's what I expect back, but I've tried to get that...

$(window).bind('load' … ); not triggering

I'm currently working at making a web application only open one instance. This is being done with cookies that are being set/checked when the app is loaded and removed when the app is closed. My logic for setting the cookies I've already worked out, but I'm having a problem getting...

Chrome extension, custom context menu item not showing [duplicate]

This question already has an answer here: Chrome extension context menu not showing up 1 answer I know this question has been asked so many times on this site, e.g. this post. However, Chrome upgrades so fast and it seems those solutions don't work for the latest version anymore....

Is there any way to detect javascript postmessages using chrome extension?

Does anybody sees a way to listen to cross iframe/window communication that is being done using the javascript postMessages ? Best would be using the chrome.debugger in the background page of an extension. I see that I can listen to HTTP-Traffic using the "Network.requestWillBeSent" and "Network.responseReceived" events. But I would...

chrome extensions Uncaught ReferenceError: $ is not defined

I am trying to make a chrome extension that uses an external javascript file that uses JQuery. But I keep getting this silly error. Screenshot of error in chrome inspector. Any help is appreciated thanks! popup.js $(document).ready(function(){ $.ajax({url: "", success: function(result){ $("#report-details").html(result); }}); }); popup.html <!doctype html> <html> <head> <title>TEST</title>...

Constantly check the length of an element and perform an action if it is ever 1

I have an element on a page that I am constantly monitoring. If at any time that length is equal to 1, it means it exists on the page (the user has logged out) and I want to prompt them with a popup to login. So at the moment I...

How to force loading images for the webpages installed “lazy load” without scrolling?

I implement a Chrome extension. The extension needs to get all images URLs of webpages. However, some webpages have "lazy load" plug-in. My question is if it is possible that I can still get URLs without required manually scrolling down?

KnockoutJS custom component loader not executing `loadViewModel`

Context I have been fiddling around and trying to create my own (just another) SPA framework. In this framework I've been trying to create a custom component loader to be able to do some dependency injection 'n stuff on the viewModels I'm loading. Used KnockoutJS version: 3.3.0 Problem The loadViewModel...

Angular Multiple ngIncludes with Transclusion on Page Losing Scope(?)

I am trying to build a modular ngInclude. By this, I mean that the ngIncluded JSP will pull in all the dependencies it needs and recompile itself before rendering. This same file is used multiple times on a single page. The main page has several tabs - all of which...

Are there any Chrome-specific techniques to scope/isolate CSS?

I'm writing a Chrome extension that injects HTML into a displayed page. I want the injected HTML to have it's own style, protected from the CSS that may be present in the host page. I've tried using conventional CSS, and still suffer from style corruption from the host page. After...

Why does chrome.tabs.create create 2 tabs?

When the chrome.tabs.create function is triggered by a message received, it creates 2 tabs. In the following demo code, 1 cat tab is created, and 2 dog tabs are created. Is this by design or is it a bug? If it is a known bug, can you provide the bug...

JQuery .find() failing on an .ajax() result

I'm working on a Chrome extension which, under certain conditions, performs a $.ajax() request and then uses information of specific elements in the returned HTML. For now, I'm simply trying to have it access the specific element and log it to the console to ensure it works correctly. To start,...

requirejs + angularjs code structure split in different files

I'm using requirejs and Angular and I'm trying to create an application structure that allows me to split every controller/services/directives etc in different files. This is the structure I'd like to achieve: src/ components/ Navigation/ index.js module.js NavigationController.js NavigationService.js In module.js I'd like to do something like this: define(['angular', './NavigationService',...

Isomorphic JavaScript with RequireJS

I have some isomorphic JavaScript. I am using RequireJS on the client side. (function() { 'use strict'; function wrapper(require) { var MyDep = require('my-dependency'); return function MyExportedFunction() { // ... }; } if ((typeof exports === 'object') && module) { module.exports = wrapper(require); // CommonJS } else if ((typeof define...

Using Youtube's Data API

I cannot figure out how to use Youtube's API V3, with Chrome's identity extension API. Is there a tutorial somewhere? I would like to start by rating a video.

Chrome Extension - How to execute a JS script on page load

The following is that I'm trying to achieve Every time '' loads, a script/function triggers. However, the functions itself reloads the page via 'location.reload();' Basically, an infinite loop of reloads. Script reloads page -> Script injected -> Script reloads page -> etc. I want the tab @ to keep...

Naming modules with RequireJS

I am trying to figure out how to name modules without using the relative path of the module itself. For example: Instead of doing this: //module is defined in app/js/routers.js define('app/js/routers',['app/js/currentView'],function(currentView) { }); I would rather do this: //module is defined in app/js/routers.js define('routers',['app/js/currentView'],function(currentView) { }); is this possible or...

AlmondJS - Require external url

In one of my AMD modules I have require(["//"]); It works with requireJS, but, when using almond, I get "Uncaught Error: undefined missing //" error. Does this mean almond does not support requiring external scripts?...

Library duplication issue using Highcharts in Jaspersoft Studio

I have a problem with Highcharts libraries. I have created various charts with the Custom Visualization tool available in Jaspersoft Studio. They do not use all the same library, e.g. I have a Bubble Map chart which uses Highmaps.js and a Stock chart which uses Highstock.js. Every report seems to...

Why `init` of shim in my require.js configuration not called?

Update: I was writing a small module to handle this csrf token problem in backbone until I got push notification of @Louis's answer. His answer is quite elegant and seems nice, but I'll leave a link to my backbone.csrf module github repo just for anyone who needs it. ==================================================================== I'm...

Simple Chrome Extension : Open an url in a new tab

I'm looking to create a "new tab" extension like Panda or the Product Hunt Extension: the user can open a new tab with my website inside, with an hidden url. I've generated my package with the awesome Extensionizr and here is my manifest.json : manifest.json { "name": "My app", "version":...

How to load ace editor with requirejs from CDN?

I am trying to load the ace editor from a CDN with requirejs. Here is a plunkr which illustrates my problem. Ace is not defined in the following case: requirejs.config({ paths: { ace: ['//'] } }) $('h1').text("loading ace..."); requirejs([ 'ace'], function(ace) { $('h1').text("ace loaded.") console.log(ace) ace.edit('#editor') return }) ...

Can Chrome extension content script access all tabs?

Basically, I want to get all the opened tabs of the browser window, from within a tab, more specifically, in content script. I tried chrome.tabs.query, it works in background script, but doesn't work in content script. So my questions are: Is there a way to do such work? Maybe an...

Show jQuery loading progress before page fully loaded

I am using requireJS domReady plug in to show jQuery loading progress on web page. Here is the code that I am using, require(['domReady'], function (domReady) { domReady(function () { //Hide jQuery loading progress }); //Show jQuery loading progress }); Problem: jQuery loading progress is showing good, but it...

Difference between local and global require in RequireJS

Using RequireJS, I don't believe I fully understand the difference between the following two different usages of 'require'. In this case, I am only talking about the browser, not node.js. One of my questions is: can I require certain dependencies synchronously on the front-end using RequireJS? first there is this:...

Mismatched anonymous define() in Chrome extension content script

I'm trying to build a Chrome extension with TypeScript. The setup is quite simple: In manifest.json { "permissions": [ "webRequest", "webRequestBlocking", "tabs", "storage", "http://*/", "https://*/*" ], "content_scripts": [ { "matches": [ "http://*/*", "https://*/*" ], "js": [ "scripts/require.js", "scripts/require-cs.js", "scripts/main.js", "scripts/contentscript.js" ], "run_at": "document_end", "all_frames": true }], } In model.ts: export...

How to do asynchronous initialization in a RequireJS module

I'm trying to create a module which need needs to fetch data from a URL before initialization is complete. I suspect I am missing something obvious but how to a make RequireJS wait until my async call is complete before the require call is satisifed. // data module (function() {...