Angular 7 TypeError:无法读取 setTitle 中未定义的属性“length”
2019-07-08
733
我的 angular 项目上出现了一条神秘的错误消息
错误处理响应:TypeError:无法读取 setTitle 中未定义的属性“length”
错误消息导致此问题
content_script.js
function setTitle(result) {
if(result[document.URL]) {
document.title = result[document.URL];
}
else {
var regex_list = result["regex"];
for (i = 0; i < regex_list.length; i += 2) {
if (document.URL.match(regex_list[i])) {
document.title = regex_list[i+1];
}
}
}
}
function onError(error) {
console.log(`Error: ${error}`);
}
function init() {
chrome.storage.sync.get(null, setTitle);
}
init();
我没有创建 content_script.js,我猜这是在构建项目时生成的
我的项目中唯一使用 setTitle 的地方是 app.component.ts
import { Component } from "@angular/core";
import { Title } from "@angular/platform-browser";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title: string = "MY TITLE";
public constructor(private titleService: Title) {}
ngOnInit() {
this.titleService.setTitle(this.title);
}
}
如果我删除 ngOnInit 内容,错误仍然会出现
编辑: setTitle 导致此代码块
title.d.ts
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Factory to create Title service.
*/
export declare function createTitle(): Title;
/**
* A service that can be used to get and set the title of a current HTML document.
*
* Since an Angular application can't be bootstrapped on the entire HTML document (`<html>` tag)
* it is not possible to bind to the `text` property of the `HTMLTitleElement` elements
* (representing the `<title>` tag). Instead, this service can be used to set and get the current
* title value.
*
* @publicApi
*/
export declare class Title {
private _doc;
constructor(_doc: any);
/**
* Get the title of the current HTML document.
*/
getTitle(): string;
/**
* Set the title of the current HTML document.
* @param newTitle
*/
setTitle(newTitle: string): void;
}
3个回答
看起来你的数组是空的:
var regex_list = result["regex"];
尝试在运行循环语句之前添加数组检查:
var regex_list = result["regex"];
if (regex_list && regex_list.length) {
for (i = 0; i < regex_list.length; i += 2) {
if (document.URL.match(regex_list[i])) {
document.title = regex_list[i+1];
}
}
}
StepUp
2019-07-08
我遇到了同样的错误,当我从 Chrome 中删除 Chrome 扩展程序“重命名标签标题”后,该错误得到了解决
Ian James
2022-07-08
没关系,我的缓存只需要清除。这种错误不会再发生了,对不起大家
Thomas Fournet
2019-07-08