Ошибка cannot read property document of null

One big difference between running hosted and running locally is the security treatment of network calls. The reference to crossdomain.php in your stack trace suggests that you’re running into this.

If so, then there are two possible solutions:

If you’re running in Flash: You need to host a crossdomain.xml file at the root of the remote domain that grants permission to the local domain (or, as in this example, everyone):

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
   <allow-access-from domain="*" />
</cross-domain-policy>

This file must always be at the root of the remote domain, e.g., http://something.com/crossdomain.xml .

If Flash is not involved, then CORS is the security mechanism responsible for blocking this call, and you need to configure the remote web server to add an Access-Control-Allow-Origin header to the response to the URL you’re reaching out to.

Access-Control-Allow-Origin: *

   novichok79

23.10.19 — 12:32

Добрый день, уважаемые коллеги.

Платформа — 1С:Предприятие 8.3 (8.3.15.1656), соответственно используется WebKit.

В обработке присваиваю полю HTML URL удаленного ресурса, 1С его успешно загружает в поле HTML документа, и делает доступным свойство «document». При открытии той же обработки в веб-клиенте, 1С загружает HTML в поле HTML документа, но программно свойство «document» у поля HTML = неопределено. Писать баг-репорт в 1С?

Кто сталкивался, помогите пожалуйста решить проблему. Заранее благодарю за помощь.

   novichok79

1 — 23.10.19 — 12:33

причем, если выкачать html документа с удаленного сервера и заполнить им данные поля HTML, то в веб-клиенте работает все, кроме ajax вызовов, из-за того, что стучусь с localhost’а.

   Garykom

2 — 23.10.19 — 12:40

Даже интересно стало, что будет если в браузере запущена 1С, в 1С запущен браузер, в котором снова запущена 1С и т.д.

Когда оно сглючит на каком этапе итерации подобной рекурсии?

   novichok79

3 — 23.10.19 — 12:43

(2) ну мне кажется что где-то при открытии обработки в 1С, который лежит в iframe.

   Случайный прохожий

4 — 23.10.19 — 12:49

Cannot read property document of null? На инфостарте прям недавно ветка поднималась (ошибка связанная с печатью из браузера). Но проблему пока не решили.

   novichok79

5 — 23.10.19 — 12:54

(4) ПолеHTML.document = Неопределено

   Cyberhawk

6 — 23.10.19 — 13:13

Ну так после 8.3.14.какой-то там это свойство упразднено

   Cyberhawk

7 — 23.10.19 — 13:15

Вместо него в определенных сценариях теперь defaultView

   novichok79

8 — 23.10.19 — 13:19

(7) defaultView это свойство поля «document», который = неопределено.

   Garykom

9 — 23.10.19 — 13:25

А чему равен «Document.defaultView» или «Документ.defaultView» ?

Может там регистрозависмость в ?

   acht

10 — 23.10.19 — 13:49

Нет там регистрозависимости. Там банальные кроссдоменные ограничения безопасности.

Когда ты работаешь через веб-клиент, у тебе пользовательский агент — сам браузер. Который смотрит на домен публикации базы 1С, на заголовки политики страницы фрейма из другого домена и говорит тебе — иди-ка ты, родной, в хрен. Открыл, понимаешь, программно интернет банк и программно же деньги тыришь, например.

А когда работаешь через клиента 1С с его полем ХТМЛ, то там пользовательский агент — приложение 1С. Которое ничего не говорит, потому что ему похрен.

   Garykom

11 — 23.10.19 — 13:55

(10) А что будет если веб-клиента 1С открыть в ie ?

   acht

12 — 23.10.19 — 14:02

(11) Это тоже браузер что-ли?

   novichok79

13 — 23.10.19 — 16:23

еще проблемка — как определить dblclick, это делать fireEvent onclick с какими-то параметрами 1С? как-то коряво получается.

   DrWatson

14 — 23.10.19 — 16:31

(0) Есть же православное свойство Документ. Это не оно?

Расширение поля формы для поля HTML-документа (Form extension for a HTML document field)

Документ (Document)

Описание:

Тип: ВнешнийОбъект.

Предоставляет доступ к HTML-документу.

  

novichok79

15 — 23.10.19 — 16:45

(14) оно

Элемент.Документ

  

novichok79

23.10.19 — 12:32

Добрый день, уважаемые коллеги.

Платформа — 1С:Предприятие 8.3 (8.3.15.1656), соответственно используется WebKit.

В обработке присваиваю полю HTML URL удаленного ресурса, 1С его успешно загружает в поле HTML документа, и делает доступным свойство «document». При открытии той же обработки в веб-клиенте, 1С загружает HTML в поле HTML документа, но программно свойство «document» у поля HTML = неопределено. Писать баг-репорт в 1С?

Кто сталкивался, помогите пожалуйста решить проблему. Заранее благодарю за помощь.

  

novichok79

1 — 23.10.19 — 12:33

причем, если выкачать html документа с удаленного сервера и заполнить им данные поля HTML, то в веб-клиенте работает все, кроме ajax вызовов, из-за того, что стучусь с localhost’а.

  

Garykom

2 — 23.10.19 — 12:40

Даже интересно стало, что будет если в браузере запущена 1С, в 1С запущен браузер, в котором снова запущена 1С и т.д.

Когда оно сглючит на каком этапе итерации подобной рекурсии?

  

novichok79

3 — 23.10.19 — 12:43

(2) ну мне кажется что где-то при открытии обработки в 1С, который лежит в iframe.

  

Случайный прохожий

4 — 23.10.19 — 12:49

Cannot read property document of null? На инфостарте прям недавно ветка поднималась (ошибка связанная с печатью из браузера). Но проблему пока не решили.

  

novichok79

5 — 23.10.19 — 12:54

(4) ПолеHTML.document = Неопределено

  

Cyberhawk

6 — 23.10.19 — 13:13

Ну так после 8.3.14.какой-то там это свойство упразднено

  

Cyberhawk

7 — 23.10.19 — 13:15

Вместо него в определенных сценариях теперь defaultView

  

novichok79

8 — 23.10.19 — 13:19

(7) defaultView это свойство поля «document», который = неопределено.

  

Garykom

9 — 23.10.19 — 13:25

А чему равен «Document.defaultView» или «Документ.defaultView» ?

Может там регистрозависмость в ?

  

acht

10 — 23.10.19 — 13:49

Нет там регистрозависимости. Там банальные кроссдоменные ограничения безопасности.

Когда ты работаешь через веб-клиент, у тебе пользовательский агент — сам браузер. Который смотрит на домен публикации базы 1С, на заголовки политики страницы фрейма из другого домена и говорит тебе — иди-ка ты, родной, в хрен. Открыл, понимаешь, программно интернет банк и программно же деньги тыришь, например.

А когда работаешь через клиента 1С с его полем ХТМЛ, то там пользовательский агент — приложение 1С. Которое ничего не говорит, потому что ему похрен.

  

Garykom

11 — 23.10.19 — 13:55

(10) А что будет если веб-клиента 1С открыть в ie ?

  

acht

12 — 23.10.19 — 14:02

(11) Это тоже браузер что-ли?

  

novichok79

13 — 23.10.19 — 16:23

еще проблемка — как определить dblclick, это делать fireEvent onclick с какими-то параметрами 1С? как-то коряво получается.

  

DrWatson

14 — 23.10.19 — 16:31

(0) Есть же православное свойство Документ. Это не оно?

Расширение поля формы для поля HTML-документа (Form extension for a HTML document field)

Документ (Document)

Описание:

Тип: ВнешнийОбъект.

Предоставляет доступ к HTML-документу.

  

novichok79

15 — 23.10.19 — 16:45

(14) оно

Элемент.Документ

I get the error: TypeError: Cannot read property ‘document’ of null on Infragistics.lob.js:880

Steps to recreate:

1: Hit script link which executes previewHTMLContent function (append the html to htmlEditor div).

2: Hit edit button which executes loadHTMLEditor function. This clears the content/styles/css of the htmlEditor div then loads the HTML editor with the content html.

3: Change the script by clicking on a new script link and the previewHTMLContent function is executed again with the new HTML

4: Hit edit button for new script. This is where the div empties out and the javascript error occurs. 

Once you load the HTMLEditor, are you unable to reload it?

HTML:

<div>
<div class=»col-md-4″>
<div class=»panel panel-default»>
<div class=»panel-heading»>
<button class=»btn btn-info pull-right» type=»button»><span class=»glyphicon glyphicon-plus»></span> Add</button>
<h3>Script Documents</h3>
<div class=»clearfix»></div>
</div>
<div class=»panel-body»>
<ul class=»nav nav-pills»>
@foreach (var script in @Model)
{
<li>
<span class=»glyphicon glyphicon-arrow-right pull-right»></span>
<a href=»BLOCKED SCRIPTvoid(0);» class=»btn btn-default btn-script» data-id=»@script.ID»>@script.Name</a>
</li>
}
</ul>
</div>
</div>
</div>
<div class=»col-md-8″>
<div class=»panel panel-default»>
<div class=»panel-heading»>
<button id=»Edit» class=»btn btn-info pull-right» type=»button» data-id=»»><span class=»glyphicon glyphicon-pencil»></span> Edit</button>
<h3>Details</h3>
<div class=»clearfix»></div>
</div>
<div class=»panel-body»>
<div id=»container»>
<div id=»htmlEditor»></div>
</div>
</div>
</div>
</div>
</div>

Javascipt:

$(function () {
$(‘a.btn-script’).click(function () {
var id = $(this).data(‘id’);
$.ajax({
url: «/Scripts/Display/»,
type: «POST»,
data: { id: id},
success: function (result) {
clearContent();
previewHTMLContent(result.script);
setEditDataId(id);
}
});
});

$(‘#Edit’).click(function () {
$.ajax({
url: «/Scripts/Display/»,
type: «POST»,
data: { id: $(this).data(‘id’) },
success: function (result) {
clearContent();
loadHTMLEditor(result.script);
}
});
});
});

function setEditDataId(id) {
$(‘#Edit’).data(‘id’, id);
}

function previewHTMLContent(script) {
var contentText = $(«<div/>»).html(script).text();
$(«#htmlEditor»).append(contentText);
}

function loadHTMLEditor(script) {
var height = $(‘html’).hasClass(‘touch’) ? 500 : 800,
contentText = $(«<div/>»).html(script).text();
var $igTBar = null;

$(«#htmlEditor»).igHtmlEditor({
height: height,
width: «98%»,
customToolbars: [
{
name: «DeleteContentButton»,
collapseButtonIcon: «ui-igbutton-collapse»,
expandButtonIcon: «ui-igbutton-expand»,
items: [{
name: «appendDeleteButton»,
type: «button»,
handler: appendDeleteButton,
scope: this,
props: {
isImage: {
value: false,
action: ‘_isSelectedAction’
},
imageButtonTooltip: {
value: «Clear all content»,
action: ‘_tooltipAction’
},
imageButtonIcon: {
value: «ui-icon-contact»,
action: ‘_buttonIconAction’
}
}
}]
}]
});

$(«#htmlEditor»).igHtmlEditor(«setContent», contentText, «html»);

changeToolbarsPosition();
}

function appendDeleteButton(ui) {
$(«#htmlEditor»).igHtmlEditor(«setContent», «», «html»);
}

function changeToolbarsPosition() {
$($(«#htmlEditor»).find(«span[id*=’insertObjectToolbar’].ui-igtoolbar»)).insertAfter($(«#htmlEditor»).find(«span[id*=’textToolbar’].ui-igtoolbar»));
}

function clearContent() {
$(«#htmlEditor»).empty();
$(«#htmlEditor»).removeClass();
$(«#htmlEditor»).removeAttr(‘style’);
}

Controller:

public ActionResult Index()
{
List<CRMScript> scripts = _CrmScriptRepository.GetAllScripts();

return View(scripts);
}

[HttpPost]
public ActionResult Display(int? id)
{
List<CRMScript> scripts = _CrmScriptRepository.GetAllScripts();

string script = scripts.FirstOrDefault(s => s.ID == id).Script;

if (script == null) HttpNotFound();

return Json(new {success = true, script});
}

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Open

phoet opened this issue

Sep 21, 2018

· 4 comments


Open

Cannot read property ‘document’ of null on browser-refresh

#301

phoet opened this issue

Sep 21, 2018

· 4 comments

Comments

@phoet

Version info

  • intercom-rails version: 0.4.0
  • Rails version: 5.2.1 (with turbolinks)

Expected behavior

no exception is thrown

Actual behavior

an exception is thrown

Steps to reproduce

  1. navigate with turbolinks
  2. open intercom window and interact (ie search FAQ)
  3. navigate without turbolinks (ie refresh the page, use the URL bar)

Logs

VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1

@phoet

the output of trackjs is a bit more helpful:

  return [".intercom-launcher-frame", "#intercom-container",
    ".intercom-messenger", ".intercom-notifications"
  ].some(function(e) {
    var t = window.parent.document.querySelector(e); // window.parent is null
    if (t) {
      var n = t.getBoundingClientRect();
      return n && n.width > 0 && n.height > 0
    }
  })

@phoet

@ghiculescu

@phoet did you end up working around this or just ignoring it?

@phoet

Neither, ignored the errors

2 participants

@phoet

@ghiculescu

TL;DR;

  • You are accessing a property of an object that is null. For example, document.getElementById(‘stuff’) returns null. So adding .value will cause the error.
  • You are trying to access a DOM element before the DOM is ready. Use onload or DOMContentLoaded.
  • Test if an object is valid before accessing its property.

There are a few variations of this error depending on the property you are trying to access. Sometimes instead of null it will say undefined. An example will be:

Uncaught TypeError: Cannot read property 'value' of null

Uncaught TypeError: Cannot read property 'innerHTML' of null

All this means is that you are trying to access a property of an object that is undefined. These usually happens when we don’t test an object before using it. Here is a common scenario.

// We want to get the value of an input. 
var inputVal = document.getElementById("input").value;

This will result in Uncaught TypeError: Cannot read property 'value' of null. The reason will be that the element with id input does not exist. Let me break it down in simpler steps;

var input = document.getElementById("input"); 
input // when this fails, it returns null. input = null
var inputVal = input.value;
// this is the same as the following. 
var inputVal = null.value;
// null does not have the property 'value'

When you break it down, the error actually makes sense. To make sure that you don’t get this error, you have to make sure that btn, or any object you use, is not null before you use it. For our example:

var input = document.getElementById("btn");
var inputVal = "";
if (input) {
    inputVal = input.value;
}

Sometimes, your object is nested deeper like Tree.folder.path. You just have to make sure that if you need to access folder, than Tree has to be defined. And if you need to access path, then folder needs to be defined.

In some cases, this error is a symptom of another issue. Why would getElementById return null if the element actually exists on the page? Probably because the function is called before the DOM is ready. Always be careful when accessing a DOM element before it is ready.


Did you like this article? You can subscribe to read more awesome ones. RSS

Sign up for the Newsletter.

Follow me on
Twitter

1. Open a panel in admin mode
2. Open «Add content» dialog on a pane
3. Select «New custom content». Window with CKEditor loaded appears:
01.png
4. Close the window using either «Close window» control or by pressing «Cancel» button.
5. Repeat adding custom content. Now the window lacks CKEditor:
50.png
and error message appears in js console:
29.png

I use jQuery 1.8 provided by latest jQuery Update dev

Tag1 supports the Drupal Project.Tag1 logo

Comments

OnkelTem’s picture

After digging in CKEditor 3.6.6.1 sources I found location where this error is triggered:

getFrameDocument : function()
		{
			var $ = this.$;

			try
			{
				// In IE, with custom document.domain, it may happen that
				// the iframe is not yet available, resulting in "Access
				// Denied" for the following property access.
				$.contentWindow.document;
			}
			catch ( e )
			{
				// Trick to solve this issue, forcing the iframe to get ready
				// by simply setting its "src" property.
				$.src = $.src;

				// In IE6 though, the above is not enough, so we must pause the
				// execution for a while, giving it time to think.
				if ( CKEDITOR.env.ie && CKEDITOR.env.version < 7 )
				{
					window.showModalDialog(
						'javascript:document.write("' +
							'<script>' +
								'window.setTimeout(' +
									'function(){window.close();}' +
									',50);' +
							'</script>")' );
				}
			}

			return $ && new CKEDITOR.dom.document( $.contentWindow.document );
		},

$ variable has iframe object. But $.contentWindow is NULL. I have no idea why this happens.

  • Log in or register to post comments

jcisio’s picture

Title: «Uncaught TypeError: Cannot read property ‘document’ of null» error when adding custom content on a panel » «Uncaught TypeError: Cannot read property ‘document’ of null» error when edit custom content pane twice
  • Log in or register to post comments

OnkelTem’s picture

I found the reason. Making a patch atm.

  • Log in or register to post comments

OnkelTem’s picture

This patch adds reaction on the ‘CToolsDetachBehaviors’ which is triggered when you close Ctools modal form (where Custom content appears). It finds and kills appropriate CKEdtior instance and now it can be relaunched correctly many times.

But this event triggered only when you close modal form using «Close Window» control button (in the upper right corner of the window). When you press «Cancel» button, this even isn’t triggered and instead — standard Drupal detach behavior hook is called which doesn’t kill the instance when «trigger» parameter equals to «serialize» (which is the case when you click «Cancel» button).

As far as I understand the correct behavior would be to kill CKEditor instance if Cancel is pressed. But I haven’t find the way to get the information whether a form was submitted using «Save» or «Cancel» button — it just not available in a detach handler (even if having form object in context parameter). So this vulgar patch most likely is wrong:

diff --git a/includes/ckeditor.utils.js b/includes/ckeditor.utils.js
index 0a2aee8..ccd7c89 100644
--- a/includes/ckeditor.utils.js
+++ b/includes/ckeditor.utils.js
@@ -333,9 +333,9 @@ window.CKEDITOR_BASEPATH = Drupal.settings.ckeditor.editor_path;
     function(context, settings, trigger){
       $(context).find("textarea.ckeditor-mod.ckeditor-processed").each(function () {
         var ta_id=$(this).attr("id");
-        if (CKEDITOR.instances[ta_id])
+        if (CKEDITOR.instances[ta_id]) {
           $('#'+ta_id).val(CKEDITOR.instances[ta_id].getData());
-        if(trigger != 'serialize') {
+        //if(trigger != 'serialize') {
           Drupal.ckeditorOff(ta_id);
           $(this).removeClass('ckeditor-processed');
         }
  • Log in or register to post comments

jcisio’s picture

I think the attached patch is a proper fix.

  • Log in or register to post comments

jcisio’s picture

$().trigger is blocking, so this one remote the unnecessary part.

  • Log in or register to post comments

OnkelTem’s picture

#5 doesn’t work for me.

1) Add custom content
2) Close using Cancel
3) Add again —> no CKEditor loaded.

UPDATED. #6 won’t work either.

  • Log in or register to post comments

jcisio’s picture

  • Log in or register to post comments

OnkelTem’s picture

  • Log in or register to post comments

jcisio’s picture

Any error? Could it be reproduced with a vanilla Drupal + CKEditor + Panels install?

I tested #6 and had different confirmations that it worked, but custom content pane edition, and with custom CTools modal. So I think you have another problem.

  • Log in or register to post comments

OnkelTem’s picture

I have no clean setup, as and I’m on Drupal + CKEditor + Panels git verions.
I believe the reason why #6 doesn’t work — it doesn’t resolve the issue «trigger = serialize» as I described in #4.

  • Log in or register to post comments

jcisio’s picture

It’s difficult to debug if we don’t have your specific environment. I think I’ll commit #6 BTW. The «serialize» event is not a problem, CKEditor is removed on the «unload» event.

  • Log in or register to post comments

OnkelTem’s picture

How comes its not a problem if CKeditor gets detach with trigger = serialize and not removing its instance? It is not unloaded. Or what is unload event?

Have you tried adding custom content, canceling it, then adding again without closing Add content dialog?

  • Log in or register to post comments

jcisio’s picture

Status: Needs review » Fixed

Ah ok. I only closed the modal then open it again, and it worked. I didn’t try the Cancel button. I think it is a bug in CTools Page Manager not to fire an appropriate event. We can’t remove the editor in the «serialize» event, to avoid reinitialisation of another editor. Try to file an issue in CTools queue. Because in fact, when you press Cancel, even the modal is not closed, its content is replaced with a different one via an AJAX request, so it should fire an event.

In wysiwyg module, the same thing happens http://drupalcode.org/project/wysiwyg.git/blob/refs/heads/7.x-2.x:/wysiw…. I’m marking this issue as fixed then (patch #6, which is a simplified version of your patch #4, has been committed as it fixes the Close button).

  • Log in or register to post comments
Status: Fixed » Closed (fixed)

Automatically closed — issue fixed for 2 weeks with no activity.

  • Log in or register to post comments

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Open

phoet opened this issue

Sep 21, 2018

· 4 comments

Open

Cannot read property ‘document’ of null on browser-refresh

#301

phoet opened this issue

Sep 21, 2018

· 4 comments

Comments

@phoet

Version info

  • intercom-rails version: 0.4.0
  • Rails version: 5.2.1 (with turbolinks)

Expected behavior

no exception is thrown

Actual behavior

an exception is thrown

Steps to reproduce

  1. navigate with turbolinks
  2. open intercom window and interact (ie search FAQ)
  3. navigate without turbolinks (ie refresh the page, use the URL bar)

Logs

VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
VM56 frame.579b2cfd.js:1 Uncaught TypeError: Cannot read property 'document' of null
    at VM56 frame.579b2cfd.js:1
    at Array.some (<anonymous>)
    at Object.v [as messengerIsVisible] (VM56 frame.579b2cfd.js:1)
    at i (VM56 frame.579b2cfd.js:1)
    at a (VM56 frame.579b2cfd.js:1)
    at VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1
v @ VM56 frame.579b2cfd.js:1
i @ VM56 frame.579b2cfd.js:1
a @ VM56 frame.579b2cfd.js:1
(anonymous) @ VM56 frame.579b2cfd.js:1

@phoet

the output of trackjs is a bit more helpful:

  return [".intercom-launcher-frame", "#intercom-container",
    ".intercom-messenger", ".intercom-notifications"
  ].some(function(e) {
    var t = window.parent.document.querySelector(e); // window.parent is null
    if (t) {
      var n = t.getBoundingClientRect();
      return n && n.width > 0 && n.height > 0
    }
  })

@phoet

@ghiculescu

@phoet did you end up working around this or just ignoring it?

@phoet

Neither, ignored the errors

2 participants

@phoet

@ghiculescu

1. Open a panel in admin mode
2. Open «Add content» dialog on a pane
3. Select «New custom content». Window with CKEditor loaded appears:
01.png
4. Close the window using either «Close window» control or by pressing «Cancel» button.
5. Repeat adding custom content. Now the window lacks CKEditor:
50.png
and error message appears in js console:
29.png

I use jQuery 1.8 provided by latest jQuery Update dev

Tag1 supports the Drupal Project.Tag1 logo

Comments

OnkelTem’s picture

After digging in CKEditor 3.6.6.1 sources I found location where this error is triggered:

getFrameDocument : function()
		{
			var $ = this.$;

			try
			{
				// In IE, with custom document.domain, it may happen that
				// the iframe is not yet available, resulting in "Access
				// Denied" for the following property access.
				$.contentWindow.document;
			}
			catch ( e )
			{
				// Trick to solve this issue, forcing the iframe to get ready
				// by simply setting its "src" property.
				$.src = $.src;

				// In IE6 though, the above is not enough, so we must pause the
				// execution for a while, giving it time to think.
				if ( CKEDITOR.env.ie && CKEDITOR.env.version < 7 )
				{
					window.showModalDialog(
						'javascript:document.write("' +
							'<script>' +
								'window.setTimeout(' +
									'function(){window.close();}' +
									',50);' +
							'</script>")' );
				}
			}

			return $ && new CKEDITOR.dom.document( $.contentWindow.document );
		},

$ variable has iframe object. But $.contentWindow is NULL. I have no idea why this happens.

  • Log in or register to post comments

jcisio’s picture

Title: «Uncaught TypeError: Cannot read property ‘document’ of null» error when adding custom content on a panel » «Uncaught TypeError: Cannot read property ‘document’ of null» error when edit custom content pane twice
  • Log in or register to post comments

OnkelTem’s picture

I found the reason. Making a patch atm.

  • Log in or register to post comments

OnkelTem’s picture

This patch adds reaction on the ‘CToolsDetachBehaviors’ which is triggered when you close Ctools modal form (where Custom content appears). It finds and kills appropriate CKEdtior instance and now it can be relaunched correctly many times.

But this event triggered only when you close modal form using «Close Window» control button (in the upper right corner of the window). When you press «Cancel» button, this even isn’t triggered and instead — standard Drupal detach behavior hook is called which doesn’t kill the instance when «trigger» parameter equals to «serialize» (which is the case when you click «Cancel» button).

As far as I understand the correct behavior would be to kill CKEditor instance if Cancel is pressed. But I haven’t find the way to get the information whether a form was submitted using «Save» or «Cancel» button — it just not available in a detach handler (even if having form object in context parameter). So this vulgar patch most likely is wrong:

diff --git a/includes/ckeditor.utils.js b/includes/ckeditor.utils.js
index 0a2aee8..ccd7c89 100644
--- a/includes/ckeditor.utils.js
+++ b/includes/ckeditor.utils.js
@@ -333,9 +333,9 @@ window.CKEDITOR_BASEPATH = Drupal.settings.ckeditor.editor_path;
     function(context, settings, trigger){
       $(context).find("textarea.ckeditor-mod.ckeditor-processed").each(function () {
         var ta_id=$(this).attr("id");
-        if (CKEDITOR.instances[ta_id])
+        if (CKEDITOR.instances[ta_id]) {
           $('#'+ta_id).val(CKEDITOR.instances[ta_id].getData());
-        if(trigger != 'serialize') {
+        //if(trigger != 'serialize') {
           Drupal.ckeditorOff(ta_id);
           $(this).removeClass('ckeditor-processed');
         }
  • Log in or register to post comments

jcisio’s picture

I think the attached patch is a proper fix.

  • Log in or register to post comments

jcisio’s picture

$().trigger is blocking, so this one remote the unnecessary part.

  • Log in or register to post comments

OnkelTem’s picture

#5 doesn’t work for me.

1) Add custom content
2) Close using Cancel
3) Add again —> no CKEditor loaded.

UPDATED. #6 won’t work either.

  • Log in or register to post comments

jcisio’s picture

  • Log in or register to post comments

OnkelTem’s picture

  • Log in or register to post comments

jcisio’s picture

Any error? Could it be reproduced with a vanilla Drupal + CKEditor + Panels install?

I tested #6 and had different confirmations that it worked, but custom content pane edition, and with custom CTools modal. So I think you have another problem.

  • Log in or register to post comments

OnkelTem’s picture

I have no clean setup, as and I’m on Drupal + CKEditor + Panels git verions.
I believe the reason why #6 doesn’t work — it doesn’t resolve the issue «trigger = serialize» as I described in #4.

  • Log in or register to post comments

jcisio’s picture

It’s difficult to debug if we don’t have your specific environment. I think I’ll commit #6 BTW. The «serialize» event is not a problem, CKEditor is removed on the «unload» event.

  • Log in or register to post comments

OnkelTem’s picture

How comes its not a problem if CKeditor gets detach with trigger = serialize and not removing its instance? It is not unloaded. Or what is unload event?

Have you tried adding custom content, canceling it, then adding again without closing Add content dialog?

  • Log in or register to post comments

jcisio’s picture

Status: Needs review » Fixed

Ah ok. I only closed the modal then open it again, and it worked. I didn’t try the Cancel button. I think it is a bug in CTools Page Manager not to fire an appropriate event. We can’t remove the editor in the «serialize» event, to avoid reinitialisation of another editor. Try to file an issue in CTools queue. Because in fact, when you press Cancel, even the modal is not closed, its content is replaced with a different one via an AJAX request, so it should fire an event.

In wysiwyg module, the same thing happens http://drupalcode.org/project/wysiwyg.git/blob/refs/heads/7.x-2.x:/wysiw…. I’m marking this issue as fixed then (patch #6, which is a simplified version of your patch #4, has been committed as it fixes the Close button).

  • Log in or register to post comments
Status: Fixed » Closed (fixed)

Automatically closed — issue fixed for 2 weeks with no activity.

  • Log in or register to post comments

  • Ошибка cannot read property createobjectasync of undefined спутник
  • Ошибка cannot read property createobjectasync of undefined как исправить
  • Ошибка cannot read properties of undefined reading createobjectasync что это
  • Ошибка cannot perform this operation on a closed dataset
  • Ошибка cannot open hasp driver